# WebSockets and Real-time Communication

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

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-websockets
Last updated: 2026-11-28

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).

**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

- WebSocket URL uses ws:// or wss:// (TLS); wss is required in production
- readyState: CONNECTING(0), OPEN(1), CLOSING(2), CLOSED(3)
- Socket.IO wraps WebSockets with fallbacks and room abstractions
- WebSockets do not automatically reconnect - implement exponential backoff

## Common follow-up questions

- How do you handle WebSocket reconnection with exponential backoff?
- What is the difference between WebSocket and HTTP/2 server push?
- When would SSE be preferable to WebSocket?

## Interview tips

- Start with the HTTP limitation (request-response) to motivate WebSocket
- Know the three options: polling, SSE, WebSocket - and when to use each
- Mention Socket.IO for practical knowledge; it shows production awareness

## Concepts covered

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

Previous: [Custom Error Types and Error Handling](https://www.internhack.in/learn/interview/javascript-interview/js-error-types) · Next: [Advanced Regular Expressions](https://www.internhack.in/learn/interview/javascript-interview/js-regex-advanced) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [JavaScript Performance Optimization](https://www.internhack.in/learn/interview/javascript-interview/js-performance-optimization)
- [Tagged Template Literals](https://www.internhack.in/learn/interview/javascript-interview/js-tagged-templates)
- [Intersection Observer and Mutation Observer](https://www.internhack.in/learn/interview/javascript-interview/js-intersection-observer)
- [Async Iterators and for await...of](https://www.internhack.in/learn/interview/javascript-interview/js-async-iterators)
- [Advanced Object Patterns and Mixins](https://www.internhack.in/learn/interview/javascript-interview/js-object-patterns)
- [ES Modules vs CommonJS](https://www.internhack.in/learn/interview/javascript-interview/js-modules-advanced)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
