Learn the concept
Event Loop & Runtime
WebSockets provide full-duplex, persistent communication between client and server over a single TCP connection. They start as an HTTP upgrade handshake, then switch to a lightweight binary-framed protocol. Use them for real-time features like chat, live notifications, collaborative editing, and live order tracking.
The WebSocket Handshake:
A WebSocket connection begins as a standard HTTP request with an Upgrade: websocket header. The server responds with 101 Switching Protocols, and from that point forward, the same TCP connection carries WebSocket frames in both directions.
Client → Server:
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Server → Client:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Persistent Full-Duplex Communication:
After the handshake, both client and server can send messages at any time without waiting for a request/response cycle. This eliminates the overhead of HTTP headers on every message (2-10 bytes per WebSocket frame vs 200-800 bytes per HTTP request) and removes the latency of establishing new connections.
WebSocket Lifecycle — readyState:
0 CONNECTING — Connection is being established1 OPEN — Connection is active, data can flow2 CLOSING — Close handshake in progress3 CLOSED — Connection is terminatedWhen to Use WebSockets vs Alternatives:
| Feature | HTTP Polling | Server-Sent Events | WebSockets | |---------|-------------|-------------------|------------| | Direction | Client → Server | Server → Client only | Bidirectional | | Connection | New per request | Persistent (one-way) | Persistent (two-way) | | Protocol | HTTP | HTTP | WS (binary frames) | | Overhead per message | High (headers) | Medium | Low (2-10 bytes) | | Browser support | Universal | Universal (except IE) | Universal | | Auto-reconnect | N/A | Built-in | Manual | | Best for | Low-frequency updates | Notifications, feeds | Chat, collaboration, gaming |
Server-Sent Events (SSE) are simpler than WebSockets for server-to-client streaming. They use standard HTTP, support automatic reconnection, and work through most proxies and CDNs. Choose SSE for one-directional real-time data (notifications, live feeds) and WebSockets when the client also needs to send real-time data.
Scaling Challenges:
wss:// (WebSocket Secure over TLS). Validate the Origin header to prevent cross-site WebSocket hijacking.const ws = new WebSocket('wss://api.example.com/live');
// Connection opened
ws.addEventListener('open', () => {
console.log('Connected');
ws.send(JSON.stringify({ type: 'subscribe', channel: 'orders' }));
});
// Receive messages
ws.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
});
// Connection closed
ws.addEventListener('close', (event) => {
console.log(`Disconnected: code=${event.code} reason=${event.reason}`);
});
// Handle errors
ws.addEventListener('error', (error) => {
console.error('WebSocket error:', error);
});
// Send data (check readyState first)
function sendMessage(message) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(message));
}
}
// Close connection gracefully
ws.close(1000, 'User navigated away');Food delivery apps use WebSockets to push real-time driver location updates to the customer's map view.
Tools like Figma and Google Docs use WebSockets to synchronize edits between multiple users in real-time.
Build a chat application with WebSocket connection, message history, typing indicators, and auto-reconnection.
Compare implementing notifications with both WebSockets and Server-Sent Events to understand trade-offs.