Skip to main content

WebSocket

WebSocket is a protocol for persistent, full-duplex communication over a single TCP connection, enabling real-time two-way data exchange.

WebSocket is a communication protocol that establishes a long-lived, bidirectional connection between a client and a server. Unlike the request-response pattern of plain HTTP, either side can send messages at any time over the same open channel.

How It Works

A WebSocket connection begins as an ordinary HTTP request that includes an Upgrade header. If the server agrees, the connection switches protocols and stays open as a full-duplex channel over the underlying TCP connection. After the handshake, both parties exchange lightweight message frames with little overhead, in text or binary form, until either side closes the connection.

Because the connection persists, the server can push data to the client without the client asking, and the client can stream data back. Production deployments add heartbeats to detect dead connections, reconnection logic, and authentication during the handshake.

Why It Matters

WebSocket enables genuinely interactive applications: chat, multiplayer games, collaborative editors, live dashboards, and trading platforms. Before it, developers simulated real-time behavior with polling or long-polling, which wasted resources and added latency.

The trade-offs are operational. Persistent connections consume server memory and complicate horizontal scaling and load balancing, since connections are stateful. For one-way server-to-client updates, the simpler server-sent events protocol is often enough. WebSocket shines when true two-way, low-latency communication is required.

Related Terms

WebSocket runs over TCP, is an alternative to server-sent events for live updates, and complements HTTP/2 in real-time architectures.