Building Real-time Applications

Modern applications require real-time data updates. Learn how to implement real-time functionality using WebSockets and Server-Sent Events.

WebSockets Implementation

WebSockets provide full-duplex communication between client and server:

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  ws.on('message', (message) => {
    // Broadcast to all connected clients
    wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(message);
      }
    });
  });
});

Server-Sent Events for One-Way Communication

For scenarios where you only need server-to-client communication, Server-Sent Events provide a simpler alternative.

Use Cases and When to Choose Each

Understanding when to use WebSockets vs Server-Sent Events vs traditional polling is crucial for optimal performance.