WebSockets and Real-time Communication

Difficulty: Intermediate

Question

What are WebSockets? How do they compare to HTTP polling and Server-Sent Events?

Answer

WebSocket is a bidirectional, persistent communication protocol over a single TCP connection. After an HTTP upgrade handshake, both client and server can push messages at any time.

Comparison: - HTTP polling: client repeatedly fetches. Simple but wastes bandwidth. - Long polling: client holds connection until data arrives. Better but still overhead. - Server-Sent Events (SSE): server pushes over HTTP, client receives only. Auto-reconnects. - WebSocket: full-duplex, lowest latency.

Use WebSocket for: chat, live dashboards, multiplayer games, collaborative editing. Use SSE for: notifications, live feeds (server-to-client only).

Code examples

WebSocket Client API

const ws = new WebSocket('wss://api.example.com/ws');

ws.addEventListener('open', () => {
  console.log('Connected');
  ws.send(JSON.stringify({ type: 'join', room: 'general' }));
});

ws.addEventListener('message', (event) => {
  const data = JSON.parse(event.data);
  console.log('Received:', data);
});

ws.addEventListener('close', (event) => {
  console.log(`Disconnected: ${event.code}`);
  setTimeout(() => reconnect(), 3000);
});

ws.addEventListener('error', (event) => {
  console.error('WebSocket error:', event);
});

function sendMessage(text) {
  if (ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({ type: 'message', text }));
  }
}

Always check readyState before sending. Implement reconnection logic for production - WebSockets do not auto-reconnect.

Server-Sent Events (SSE)

const evtSource = new EventSource('/api/events');

evtSource.addEventListener('update', (e) => {
  const data = JSON.parse(e.data);
  console.log('Update:', data);
});

// EventSource auto-reconnects - no manual logic needed
evtSource.addEventListener('error', () => {
  console.log('Reconnecting...');
});

// SSE vs WebSocket comparison
const comparison = [
  { protocol: 'Polling',   direction: 'Client→Server', latency: 'High',   complexity: 'Low' },
  { protocol: 'SSE',       direction: 'Server→Client', latency: 'Low',    complexity: 'Low' },
  { protocol: 'WebSocket', direction: 'Bidirectional', latency: 'Lowest', complexity: 'High' }
];
console.table(comparison);

SSE is simpler and auto-reconnects but is one-directional. WebSocket enables full bidirectional communication.

Key points

Concepts covered

WebSocket, HTTP Polling, SSE, Real-time, Socket.IO