The WebSocket protocol (RFC 6455) enables full-duplex, bidirectional communication between a client and a server over a single, long-lived TCP connection. Unlike HTTP, which follows a request–response model (the client always initiates), WebSocket allows both sides to send messages independently at any time after the connection is established.
HTTP Polling vs WebSocket
- HTTP Short Polling — Client repeatedly sends requests every N seconds asking "anything new?". Wasteful and adds latency.
- HTTP Long Polling — Client sends a request; the server holds it open until data is available. Better, but still has overhead per message.
- WebSocket — One handshake, then a persistent connection. Messages flow instantly in both directions with minimal overhead.
WebSocket Handshake
A WebSocket connection starts as an HTTP/1.1 upgrade request:
GET /chat HTTP/1.1
Upgrade: websocket
Connection: Upgrade
The server responds with 101 Switching Protocols and the connection is upgraded.
Use Cases
- Live chat applications.
- Real-time dashboards and analytics.
- Multiplayer browser games.
- Collaborative editing (Google Docs-style).
- Financial tickers and live sports scores.