An Introduction to WebSockets for Real-Time Apps

HTTP was built around request-response: the client asks, the server answers, and the connection closes. That model breaks down the moment you need the server to push data the instant it happens — a chat message, a live price update, a multiplayer game state. WebSockets solve exactly that.

One Handshake, Then a Persistent Connection

A WebSocket connection starts as a normal HTTP request with an Upgrade: websocket header. Once the server agrees, the connection switches protocols and stays open — either side can send messages at any time, with none of HTTP’s per-request overhead.

A Minimal WebSocket Server

const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (socket) => {
    console.log('Client connected');

    socket.on('message', (data) => {
        // Broadcast to every other connected client
        wss.clients.forEach((client) => {
            if (client !== socket && client.readyState === 1) {
                client.send(data.toString());
            }
        });
    });

    socket.on('close', () => console.log('Client disconnected'));
});

Connecting from the Browser

const socket = new WebSocket('ws://localhost:8080');

socket.onopen = () => socket.send('Hello, server!');
socket.onmessage = (event) => console.log('Received:', event.data);
socket.onclose = () => console.log('Connection closed');

Handling Reconnection

Real networks drop connections. Production WebSocket clients need explicit reconnection logic with backoff, since the browser API doesn’t retry automatically:

function connect() {
    const socket = new WebSocket('ws://localhost:8080');
    socket.onclose = () => {
        console.log('Disconnected, retrying in 2s...');
        setTimeout(connect, 2000);
    };
    return socket;
}
connect();

When to Reach for WebSockets vs Alternatives

Use WebSockets for genuinely bidirectional, high-frequency communication. For simpler server-to-client-only push (notifications, live feed updates), Server-Sent Events are a lighter-weight option that reuses plain HTTP and reconnects automatically — worth considering before defaulting to WebSockets for every “real-time” feature.