What is WebSocket — Simple Explanation with Examples
WebSocket is a protocol that enables persistent, full-duplex communication between a client (typically a browser) and a server over a single TCP connection. Unlike HTTP’s request-response pattern, WebSocket allows either party to send data at any time.
What You’ll Learn
This article covers how WebSocket differs from HTTP polling, the handshake process, a working code example in JavaScript and Node.js, and real-world use cases. WebSocket powers real-time features in apps like Slack, Figma, and Google Docs.
The Problem WebSocket Solves
HTTP is a request-response protocol: the client sends a request, and the server sends a response. This works fine for loading web pages, but fails for real-time scenarios:
- A chat app — when User B sends a message, User A’s browser needs to know immediately.
- A stock ticker — prices change multiple times per second.
- A collaborative document — one user’s edits must appear on other screens instantly.
With plain HTTP, developers tried polling: the client sends HTTP requests every few seconds asking “any updates?”. This wastes bandwidth, creates latency (worst case = poll interval), and puts unnecessary load on the server.
WebSocket solves this by establishing a persistent connection. Once open, either side can push messages freely with minimal overhead.
The Phone Call vs Letters Analogy
HTTP is like sending letters (postal mail):
- You write a letter (request), mail it, and wait for a reply (response).
- Each letter requires a new envelope, stamp, and trip to the post office.
- To check for updates, you keep sending letters: “Any mail for me?” (polling).
- Inefficient and slow for real-time conversation.
WebSocket is a phone call:
- You dial (connect), the other person picks up (handshake).
- Once connected, you both talk freely, back and forth, instantly.
- The line stays open until someone hangs up.
- No envelopes, no stamps, no polling.
How WebSocket Works: The Handshake
A WebSocket connection starts with an HTTP upgrade handshake, then switches to the WebSocket protocol.
1. Client sends upgrade request
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 132. Server responds with upgrade
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=After the 101 response, the connection upgrades. From this point, frames flow bidirectionally without HTTP headers overhead.
ws:// vs wss://
| Scheme | Protocol | Security |
|---|---|---|
ws:// | Unencrypted WebSocket | Plain text |
wss:// | WebSocket over TLS | Encrypted (like HTTPS) |
Always use wss:// in production. It provides encryption and avoids issues with proxies that block non-TLS connections.
Example: WebSocket Chat with Node.js and JavaScript
Server (Node.js with ws library)
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
// Send a welcome message to the connected client
ws.send(JSON.stringify({
type: 'system',
message: 'Welcome to the chat!'
}));
// Broadcast incoming messages to all clients
ws.on('message', (data) => {
const message = data.toString();
console.log(`Received: ${message}`);
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
type: 'chat',
message,
timestamp: new Date().toISOString()
}));
}
});
});
ws.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server running on ws://localhost:8080');Client (Browser JavaScript)
const ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
console.log('Connected to server');
ws.send('Hello from the client!');
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(`${data.type}: ${data.message}`);
// Display in chat UI
};
ws.onclose = () => {
console.log('Disconnected from server');
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
// Send a message
function sendMessage(text) {
if (ws.readyState === WebSocket.OPEN) {
ws.send(text);
}
}Expected console output:
Connected to server
system: Welcome to the chat!
chat: Hello from the client!Reconnection Handling
WebSocket connections can drop due to network issues. Production code should auto-reconnect:
function connect() {
const ws = new WebSocket('wss://chat.example.com');
ws.onclose = () => {
console.log('Connection lost. Reconnecting in 3 seconds...');
setTimeout(connect, 3000);
};
ws.onerror = () => {
ws.close();
};
return ws;
}
const socket = connect();Exponential backoff (1s, 2s, 4s, 8s…) is a more robust strategy to avoid overwhelming the server during an outage.
HTTP Polling vs WebSocket
| Aspect | HTTP Polling | WebSocket |
|---|---|---|
| Latency | Interval-based (e.g., 5s) | Sub-second, real-time |
| Overhead | Full HTTP headers per request | Minimal frame header (2 bytes) |
| Server load | High (constant new connections) | Low (persistent connection) |
| Direction | Client-initiated only | Bidirectional |
| Network | Works through all proxies | Requires WS-aware proxies |
| Browser support | Universal | Modern browsers (IE 10+) |
Common Use Cases
Chat applications — Slack, Discord, WhatsApp Web all use WebSocket for instant message delivery. Messages appear without refreshing or polling.
Live notifications — Social media notifications, email alerts, and system monitoring dashboards push updates via WebSocket, replacing browser notification polling.
Real-time gaming — Multiplayer browser games use WebSocket for low-latency state synchronization — player positions, scores, game events.
Stock tickers and financial data — Trading platforms stream price updates via WebSocket. Latency measured in milliseconds matters for trading decisions.
Collaborative editing — Google Docs, Figma, and Notion use WebSocket (or WebRTC) to sync edits between users in real time.
FAQ
Related Terms
What is an API — What is a REST API — What is GraphQL — What is a Microservice
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro