Browser APIs & Web APIs
WebSockets
Master full-duplex real-time communication in JavaScript. Learn to open WebSocket connections, exchange JSON payloads, handle reconnections, and close sockets.
1. Introduction
Traditional HTTP requests are unidirectional: the client requests data, and the server responds. WebSockets provide a persistent, bi-directional, full-duplex communication channel over a single TCP connection, allowing real-time data exchange between the client and server.
2. Why It Matters
Polling the server repeatedly for updates (like checking for new chat messages every 2 seconds) wastes bandwidth and server resources. WebSockets solve this by allowing the server to push updates to the client instantly the moment data changes.
3. Real-World Analogy
Think of Communication Channels:
- HTTP (Postal Mail): You mail a letter asking for updates. The recipient receives it, writes a response, and mails it back. You must send a new letter every time you want to check for updates.
- HTTP Polling (Asking Repeatedly): Asking "Are we there yet? Are we there yet? Are we there yet?" repeatedly. Most requests return "No", wasting energy and bandwidth.
- WebSocket (Active Phone Call): You dial the number and establish a call. Both parties keep their phones at their ears. Either party can speak or listen instantly. The connection remains open until you hang up.
4. The WebSocket API
WebSockets use custom schemes: ws:// (unsecure) or wss:// (secure). The connection lifecycle is managed using event listeners:
5. Practical Example
This script demonstrates implementing a WebSocket client with automatic reconnection logic if the connection is lost:
6. Common Mistakes
- Trying to send data before the connection is open: Calling
socket.send()immediately after creating the WebSocket object throws an InvalidStateError because the connection is still in the connecting state. Wait for theopenevent before sending messages. - Using unsecure connections (ws://) in production: Browsers block unsecure WebSocket connections on secure (HTTPS) pages. Always use secure connections (wss://) in production.
7. Quick Quiz
Q1: What happens if you call socket.send() immediately after executing new WebSocket()?
A) The message is queued and sent automatically when the connection opens
B) It throws an InvalidStateError because the connection is not open yet
Answer: B — Calling send() before the WebSocket's readyState is open throws an InvalidStateError. You must wait for the open event.
8. Scenario-Based Challenge
The Real-Time Stock Price Dashboard:
An application displays real-time stock prices. The updates are pushed via WebSockets. If the connection fails or drops, try to reconnect, but increase the delay between retries exponentially (exponential backoff) to prevent overloading the server. Write the connection manager logic.
9. Debugging Exercise
Explain why this messaging helper throws an error, and how to fix it:
const ws = new WebSocket('wss://api.site/updates');
function sendLog(msg) { // Bug: throws InvalidStateError if called immediately! ws.send(JSON.stringify({ log: msg })); } sendLog('User clicked search');
View Solution
Diagnosis: The connection is asynchronous. The script calls sendLog() immediately after creating the WebSocket, before the connection is established (readyState is still CONNECTING).
Fix: Wrap the message in a state check or queue messages if the connection is not open yet, executing them once the connection opens:
const ws = new WebSocket('wss://api.site/updates'); const queue = [];ws.addEventListener('open', () => { // Flush queued logs while (queue.length > 0) { ws.send(queue.shift()); } });
function sendLog(msg) { const payload = JSON.stringify({ log: msg }); if (ws.readyState === WebSocket.OPEN) { ws.send(payload); } else { queue.push(payload); // Queue message } }
10. Interview Questions
🟢 Q1: Compare WebSockets with HTTP polling and Server-Sent Events (SSE).
Answer:
• HTTP Polling: The client requests data repeatedly. Most requests return empty responses, wasting bandwidth and resources.
• Server-Sent Events (SSE): A unidirectional channel where only the server can push updates to the client. It uses standard HTTP and supports automatic reconnection out of the box.
• WebSockets: A bi-directional, full-duplex channel where both client and server can send messages. It uses a custom TCP-based protocol and is best for interactive apps (like chat or gaming).
11. Production Considerations
- • Reconnection Strategy: Always implement a reconnection strategy (like exponential backoff) with jitter to prevent a stampeding herd problem (where hundreds of clients try to reconnect to the server simultaneously after a brief outage).