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:

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

Polling vs long polling vs WebSocket. Switch the transport under Tweak and compare requests and delay.
  1. Short polling: Repeated requests; most return nothing; news waits for the next poll.
  2. Long polling: The server holds the request until there's news, then the client re-asks.
  3. WebSocket handshake: One HTTP Upgrade request, answered with 101 Switching Protocols.
  4. Full duplex: Both sides send frames any time over one connection.

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

Common follow-up questions

Interview tips

Concepts covered

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

More JavaScript Interview questions