Why This Matters
Standard HTTP follows a strict request-response pattern: the client asks, the server answers, and the connection is done. But what if the server needs to push data to the client without being asked? Think of a chat application, a live sports scoreboard, or a stock ticker. Polling the server every second wastes bandwidth and adds latency.
A WebSocket solves this by upgrading an HTTP connection into a persistent, full-duplex channel. Both the client and server can send messages at any time without waiting for a request. This enables real-time communication with minimal overhead -- once the connection is open, messages flow freely in both directions.
Define Terms
Visual Model
The full process at a glance. Click Start tour to walk through each step.
WebSockets upgrade an HTTP connection to a persistent, bidirectional channel for real-time communication.
Code Example
// WebSocket client in the browser
const ws = new WebSocket("wss://echo.websocket.org");
// Connection opened
ws.addEventListener("open", () => {
console.log("Connected!");
ws.send("Hello, server!");
});
// Listen for messages from the server
ws.addEventListener("message", (event) => {
console.log("Received: " + event.data);
});
// Handle connection close
ws.addEventListener("close", (event) => {
console.log("Disconnected: code=" + event.code);
});
// Handle errors
ws.addEventListener("error", (error) => {
console.log("Error: " + error.message);
});
// Send a message later
setTimeout(() => {
ws.send(JSON.stringify({ type: "chat", text: "Hi!" }));
}, 1000);
// Close the connection
setTimeout(() => ws.close(), 5000);
// --- Simple message protocol ---
// Define message types as a protocol
function sendMessage(ws, type, payload) {
ws.send(JSON.stringify({ type, payload, timestamp: Date.now() }));
}
function handleMessage(data) {
const msg = JSON.parse(data);
switch (msg.type) {
case "chat":
console.log("Chat: " + msg.payload.text);
break;
case "notification":
console.log("Alert: " + msg.payload.message);
break;
case "ping":
console.log("Pong!");
break;
default:
console.log("Unknown type: " + msg.type);
}
}
// Usage
handleMessage(JSON.stringify({ type: "chat", payload: { text: "Hi" } }));
handleMessage(JSON.stringify({ type: "notification", payload: { message: "New update" } }));Interactive Experiment
Try these exercises:
- Open your browser developer tools (Network tab), filter by "WS", and visit a site that uses WebSockets (e.g., a chat app). Watch the messages flow in real time.
- Modify the
handleMessagefunction to support a new message type called "typing" that prints which user is currently typing. - Implement a reconnection strategy: if the WebSocket closes unexpectedly, try to reconnect after 1 second, then 2 seconds, then 4 seconds (exponential backoff).
- Compare the overhead: if you need server updates every second, calculate the total bytes for 60 seconds of HTTP polling vs one WebSocket connection.
Quick Quiz
Coding Challenge
Write a class called `MessageBroker` that simulates a publish-subscribe messaging system (like what WebSocket servers use internally). It should support: (1) `subscribe(channel, callback)` -- register a callback for a channel, (2) `publish(channel, message)` -- send a message to all subscribers of that channel, (3) `unsubscribe(channel, callback)` -- remove a callback from a channel. The `publish` method should return the number of subscribers notified.
Real-World Usage
WebSockets power the real-time features of modern applications:
- Chat applications: Slack, Discord, and WhatsApp Web use WebSockets to deliver messages instantly without polling.
- Live dashboards: Monitoring tools like Grafana and stock trading platforms stream live data to the browser over WebSockets.
- Multiplayer games: Online games use WebSockets (or similar protocols) for low-latency player state synchronization.
- Collaborative editing: Google Docs and Figma use WebSocket-like connections to sync changes between collaborators in real time.
- Server-Sent Events (SSE): A simpler alternative for server-to-client streaming (one-directional). Used when the client does not need to send data back.
- Socket.IO: A popular library that adds automatic reconnection, fallback to HTTP polling, and room-based broadcasting on top of raw WebSockets.