RFC 6455 Specification

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

FieldSizePurpose
FIN1 bit1 marks the final fragment of a message.
Opcode4 bits0x1 text, 0x2 binary, 0x8 close, 0x9 ping, 0xA pong.
MASK1 bit1 for client-to-server frames; 0 for server-to-client frames.
Payload Len7 / 16 / 64 bits0–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