HTTP polling vs WebSockets, the handshake, when to use real-time.
Traditional web communication works on a request/response cycle: your browser asks, the server answers, and the connection closes. If you want new data, you have to ask again. This is HTTP polling — and for real-time features it's wasteful and slow.
WebSockets solve this by keeping the connection open. Once the initial handshake completes, both client and server can send messages at any time without the overhead of new HTTP connections. This is what powers chat apps, live dashboards, multiplayer games, and collaborative editors.
WebSocket connections start with an HTTP upgrade request. The client sends a normal GET request with special headers: Upgrade: websocket and Connection: Upgrade. If the server supports WebSockets, it responds with status 101 Switching Protocols and the connection upgrades.
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
The ws package is the lowest-level WebSocket library for Node.js. It's what Socket.io is built on top of. Understanding it first makes everything else clearer.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (data) => {
const message = data.toString();
console.log('Received:', message);
// Echo back to sender
ws.send(`Server received: ${message}`);
});
ws.on('close', () => {
console.log('Client disconnected');
});
// Send a welcome message immediately
ws.send('Welcome! Connection established.');
});
console.log('WebSocket server running on ws://localhost:8080');
WebSocket connections can silently drop without either party knowing. The WebSocket protocol has built-in ping/pong frames for heartbeats — the server periodically sends a ping, and the client must respond with a pong. If no pong arrives, the server knows the connection is dead.
const HEARTBEAT_INTERVAL = 30000; // 30 seconds
wss.on('connection', (ws) => {
ws.isAlive = true;
ws.on('pong', () => {
ws.isAlive = true; // Reset on pong
});
});
// Check all connections every 30 seconds
const interval = setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) {
return ws.terminate(); // Dead connection
}
ws.isAlive = false;
ws.ping(); // Send ping
});
}, HEARTBEAT_INTERVAL);
npm init -y && npm install ws in a new folder.server.js.const ws = new WebSocket('ws://localhost:8080'); ws.onmessage = e => console.log(e.data);ws.send('Hello WebSocket!');ws library gives you raw WebSocket access in Node.js.