tezvyn:

The WebSocket Protocol

AI-drafted, machine-checkedbeginner

WebSocket (RFC 6455) is a protocol providing full-duplex, persistent communication over a single TCP connection. It begins as an HTTP request that upgrades, then both client and server can send messages anytime, enabling real-time apps without HTTP's…

WHY IT EXISTS: Plain HTTP is request-response and client-initiated: the server cannot push data unless the client asks. Building real-time features on HTTP meant hacks like short polling (repeatedly asking 'anything new?') or long polling, both wasteful in latency and overhead. WebSocket was created to give a true bidirectional, persistent connection so servers can push to clients the instant something happens.

THE MENTAL MODEL: Think of HTTP as mailing letters back and forth, one request per reply, versus WebSocket as opening a phone line that stays connected so either party can speak at any moment. It is full-duplex (both directions simultaneously) and persistent (one connection reused for the whole session).

HOW IT WORKS: The connection begins as an ordinary HTTP request carrying an Upgrade: websocket header and a Connection: Upgrade header, plus a Sec-WebSocket-Key. If the server agrees, it responds with status 101 Switching Protocols, and the same TCP connection is now a WebSocket. From then on, data travels as lightweight binary frames rather than HTTP messages, so there are no repeated headers per message. Either side can send text or binary frames at any time, plus control frames for ping/pong (keepalive) and close. The URL schemes are ws:// and wss:// (the latter being WebSocket over TLS).

WHEN IT MATTERS: Use WebSocket when the server must push updates with low latency and high frequency: chat and messaging, live sports or stock tickers, collaborative editors, multiplayer games, and live dashboards. It is overkill for occasional updates, where simpler approaches like server-sent events or periodic polling suffice, and it adds complexity around connection state, reconnection, and scaling across servers.

ONE CONCRETE EXAMPLE: In a chat app, each browser opens one WebSocket to the server. When Alice sends a message, it travels up her socket; the server immediately pushes it down Bob's already-open socket, so Bob sees it instantly with no polling. In Node.js this is typically built with a library like ws or Socket.IO layered on top of the HTTP server.

Read the original → datatracker.ietf.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.