The Runtime Theory

WebSocket Session Flow: Upgrade Handshake, Frames, Ping-Pong, and Close

Trace a WebSocket session from the HTTP 101 upgrade and Sec-WebSocket-Accept through masked frames, ping-pong keepalive, and the close handshake.

The Runtime Theory Team08 stages

trace / request.md

HTTP UPGRADEREQUEST101 SWITCHINGPROTOCOLSFRAME STRUCTURECLIENT SENDSMESSAGESSERVER PUSHESMESSAGESPING/PONGKEEPALIVECLOSE HANDSHAKESESSION TORN DOWN

readyThe client sends a normal HTTP GET with Connection: Upgrade, Upgrade: websocket, and Sec-WebSocket-Key — 16 random bytes base64-encoded. The server sees this as HTTP until it answers.

A WebSocket is HTTP for exactly one request — the upgrade. The client sends an ordinary GET with the upgrade headers, the server validates the Sec-WebSocket-Key against the RFC 6455 GUID, and a 101 response converts the socket into a frame stream. From that point the HTTP rules are gone: no request-response pairing, either side sends whenever it has data.

Frames are the protocol's grammar. An opcode says what the payload is, a FIN bit marks the end of a fragmented message, and the mask bit — required client-to-server only — is the machine's defense against proxy cache-poisoning. Ping and pong are the session's heartbeat: idle TCP connections get reaped by middleboxes, so the ping cadence is what actually keeps the stream alive. The close handshake matters because a bare TCP FIN cannot carry a reason code — the close frame tells the peer whether the end was clean or an error, and only then does the connection die.