In revision.
Crisp5 min readGo deeper →

WebSocket protocol

WebSocket upgrades an HTTP connection into a full-duplex framed channel. One TCP connection, both sides speak anytime.

WebSocket is RFC 6455. It starts as an HTTP/1.1 GET with Upgrade: websocket. The server responds 101 Switching Protocols. After that, the TCP connection carries WebSocket frames in both directions. Both sides can send any time. No more request-response.

The handshake

Client sends:

GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13

Server responds:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

Sec-WebSocket-Accept is SHA1(Key + magic-string) base64. This is purely to verify both sides actually speak WebSocket, not to authenticate.

WebSocket handshake and bidirectional frames

Frame format

Tiny: 2-byte minimum header, then payload. Includes:

  • FIN bit (last frame of message).
  • Opcode (text, binary, close, ping, pong).
  • Mask bit (set on client-to-server frames; server-to-client unmasked).
  • Payload length (7, 16, or 64 bit).
  • Masking key if masked.
  • Payload.

Frames combine into messages. Big messages can fragment across frames.

Why masking

Client-to-server frames are XOR-masked with a random key. This is not security; it is to prevent cache poisoning attacks against intermediaries that might misinterpret WebSocket bytes as HTTP. Server-to-client frames are unmasked.

Closing

Either side sends a close frame (opcode 0x8) optionally with a status code (1000 normal, 1001 going away, 1006 abnormal closure). The other replies with close, then TCP FIN.

What WebSocket gives you

  • Full-duplex over one TCP connection.
  • Low per-message overhead (2-14 byte header).
  • Works through HTTP proxies (because of the Upgrade dance).
  • Native browser support since 2011.

What WebSocket does not give you

  • Authentication: do it in the upgrade request (cookie, Authorization header).
  • Reconnection: implement client-side with backoff.
  • Backpressure: handle on send side, or use a library that does.
  • Message ordering across connections: only ordered within one connection.
  • Multiplexing: one logical stream per connection. Use subprotocols like SignalR or Phoenix Channels for multiplexing.

Learn more