Understanding WebSocket Protocol
1. Understanding Protocol Basics
WebSocket (RFC 6455) is a full-duplex, bidirectional TCP-based protocol over a single long-lived connection, initiated by an HTTP/1.1 Upgrade handshake. Schemes: ws:// (port 80) and wss:// (port 443, TLS).
| Property | Value | Description |
|---|---|---|
| RFC | 6455 | Core protocol specification |
| Transport | TCP | Persistent single connection |
| Direction | Full-duplex | Both peers send anytime |
| Schemes | ws, wss | Plain / TLS-encrypted |
| Default Ports | 80 / 443 | HTTP / HTTPS aligned |
| Framing | Binary frames | Text (UTF-8) or binary payloads |
| Max Frame | 2^63 bytes | 64-bit extended length |
| Sub-protocol | Sec-WebSocket-Protocol | Application-level protocol |
2. Understanding Handshake Process
| Header | Direction | Purpose |
|---|---|---|
Upgrade: websocket | Client | Request protocol switch |
Connection: Upgrade | Client | Signal upgrade intent |
Sec-WebSocket-Key | Client | Random 16-byte base64 nonce |
Sec-WebSocket-Version: 13 | Client | Protocol version |
Sec-WebSocket-Protocol | Both | Subprotocol negotiation |
Sec-WebSocket-Extensions | Both | Extension negotiation (e.g. permessage-deflate) |
Sec-WebSocket-Accept | Server | SHA-1(key + GUID) base64 |
101 Switching Protocols | Server | Handshake success status |
Example: Raw Handshake
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Sec-WebSocket-Protocol: chat.v2
Origin: https://app.example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat.v2
3. Understanding Frame Structure
| Field | Bits | Description |
|---|---|---|
| FIN | 1 | Final fragment flag |
| RSV1-3 | 3 | Reserved (used by extensions) |
| Opcode | 4 | 0x0 cont, 0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong |
| MASK | 1 | 1 for client→server (required) |
| Payload len | 7 / 7+16 / 7+64 | Length encoding |
| Masking-key | 0 / 32 | XOR key when MASK=1 |
| Payload | variable | Application data |
4. Understanding Connection States
| Constant | Value | Meaning |
|---|---|---|
CONNECTING | 0 | Handshake in progress |
OPEN | 1 | Ready to send/receive |
CLOSING | 2 | Close frame sent, awaiting response |
CLOSED | 3 | Underlying TCP closed |
5. Comparing WebSocket vs HTTP
| Aspect | WebSocket | HTTP/1.1 |
|---|---|---|
| Direction | Bidirectional | Client → Server |
| Connection | Persistent | Request/response |
| Overhead | 2-14 bytes/frame | ~500+ bytes/header |
| Latency | Low (no handshake per msg) | Higher |
| Caching | No | Yes |
| Use Case | Realtime | Document/API fetch |
6. Comparing WebSocket vs SSE
| Feature | WebSocket | SSE |
|---|---|---|
| Direction | Bidirectional | Server → Client only |
| Protocol | ws/wss (TCP) | HTTP |
| Binary | Native | Text only (base64 workaround) |
| Auto-reconnect | Manual | Built-in |
| Proxy support | May require config | Works through any HTTP proxy |
| Max connections | High | Limited per origin (HTTP/1.1: ~6) |
7. Comparing WebSocket vs Long Polling
| Aspect | WebSocket | Long Polling |
|---|---|---|
| Connections | 1 persistent | Repeated HTTP |
| Latency | ~ms | Network RTT per msg |
| Server load | Low | High (connection churn) |
| Header overhead | Minimal | Full headers each request |
| Implementation | Native API | Trivial fallback |
8. Understanding Use Cases
| Use Case | Why WebSocket |
|---|---|
| Chat / Messaging | Bidirectional, low latency |
| Live trading / quotes | Sub-second updates, server push |
| Multiplayer games | Low overhead, binary frames |
| Collaborative editing | CRDT/OT delta sync |
| IoT telemetry | Persistent device→server channel |
| Live dashboards | Server-initiated updates |
| WebRTC signaling | Out-of-band SDP/ICE exchange |
9. Understanding Protocol Limitations
| Limitation | Detail |
|---|---|
| No request/response | Must be modeled at app level |
| No HTTP semantics | No caching, no status codes per msg |
| No multiplexing | One logical channel per connection (HTTP/2 push N/A) |
| Stateful | Hard to scale horizontally without sticky sessions/pub-sub |
| Proxy traversal | Some intermediaries strip Upgrade headers |
| Reconnection | Manual logic required |
10. Understanding Browser Support
| Feature | Support | Notes |
|---|---|---|
| WebSocket API | All Browsers | Chrome 16+, FF 11+, Safari 7+, Edge 12+ |
| Binary (ArrayBuffer/Blob) | All Browsers | Set binaryType |
| permessage-deflate | Modern Browsers | Negotiated; Safari has quirks |
| WebSocketStream EXPERIMENTAL | Experimental | Chrome behind flag |
| Workers/Service Workers | All Browsers | Service Workers cannot hold open WS |