WebSockets & Wire Framing
The WebSocket protocol (RFC 6455) opens a full-duplex, two-way message channel over a single TCP socket. After an initial HTTP/1.1 upgrade handshake, both sides exchange compact framed messages without resending HTTP headers.
1. The HTTP/1.1 Upgrade Handshake
Every WebSocket starts as an HTTP/1.1 GET request with Upgrade: websocket, Connection: Upgrade, and a random 16-byte base64 Sec-WebSocket-Key.
GET /events/stream HTTP/1.1
Host: stream.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
If accepted, the server replies with 101 Switching Protocols and switches the TCP socket to binary framing.
2. Sec-WebSocket-Accept Validation
The server joins the client's key with 258EAFA5-E914-47DA-95CA-C5AB0DC85B11, hashes it with SHA-1, and base64-encodes the result.
const crypto = require("crypto");
function computeAcceptHeader(clientKey) {
const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
return crypto.createHash("sha1").update(clientKey.trim() + GUID).digest("base64");
}
3. Binary Wire Frame Layout
| Field | Size | Purpose |
|---|---|---|
FIN | 1 bit | 1 marks the final fragment of a message. |
Opcode | 4 bits | 0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong. |
MASK | 1 bit | 1 for client-to-server frames; 0 for server-to-client frames. |
Payload Len | 7 / 16 / 64 bits | 0–125 fits in 7 bits; 126 uses 16 bits; 127 uses 64 bits. |
4. Browser Client Example
const ws = new WebSocket("wss://stream.example.com/events");
ws.binaryType = "arraybuffer";
ws.addEventListener("open", () => ws.send(JSON.stringify({ type: "subscribe" })));
ws.addEventListener("message", (ev) => console.log("Message:", ev.data));
5. Heartbeats & Close Codes
1000 Normal Closure— Clean shutdown after completing the session.1001 Going Away— Tab closed or server restarting.1006 Abnormal Closure— TCP socket dropped without a close frame.