WebSocket Real-time Apps: Node.js Implementation

Build real-time applications with WebSockets.

Implement live updates and notifications.

Server Setup

const wss = new WebSocketServer({ port: 8080 });

wss.on(‘connection’, (ws) => {

ws.on(‘message’, (message) => {

console.log(‘Received:’, message);

ws.send(‘Hello from server’);

});

});

Client

const ws = new WebSocket(‘ws://localhost:8080’);

ws.onopen = () => ws.send(‘Hello!’);

ws.onmessage = (event) => console.log(event.data);

Socket.io for Production

const io = require(‘socket.io’)(server);

io.on(‘connection’, (socket) => {

socket.on(‘event’, (data) => {/* handle */});

});

Conclusion

WebSockets enable real-time features!

Leave a Comment