WebSockets
WebSockets (RFC 6455) provide full-duplex, message-oriented communication between a browser and a server over a single TCP connection — without the overhead of repeated HTTP requests.
The opening handshake
A WebSocket connection starts as an HTTP/1.1 request with an Upgrade header. The client offers a random Sec-WebSocket-Key; the server returns its hash (SHA-1 + magic GUID) in Sec-WebSocket-Accept.
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Frame format
After the handshake, both sides exchange frames:
- FIN bit — last frame of a message.
- Opcode — 0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong.
- Mask — required on client→server frames (XOR with 4-byte key).
- Payload length — 7 bits, or 16/64-bit extended length.
Control frames
Close(0x8): optional status code + UTF-8 reason. Either side may initiate.Ping(0x9) /Pong(0xA): keep-alive. Pongs may be unsolicited.
WebSockets are not HTTP/2 streams. Browsers still open WebSocket connections over HTTP/1.1. WebSockets over HTTP/2 (RFC 8441) requires explicit server opt-in via the
SETTINGS_ENABLE_CONNECT_PROTOCOL setting.
Common use cases
- Chat and presence systems.
- Real-time dashboards and metrics.
- Collaborative editing (in combination with CRDTs / OT).
- Live multiplayer game state.