Skip to content
WebSocket Upgrade Handshake
step 1/5

Reading — step 1 of 5

Read

~1 min readCaching, Compression & Beyond

WebSocket Upgrade Handshake

WebSocket (RFC 6455) hitches a ride on HTTP: a regular HTTP/1.1 request asks to switch protocols, and from then on the same TCP connection carries bidirectional binary frames instead of HTTP messages. Real-time chat, collaborative editing, multiplayer games — they all use this.

Client request

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

Server response

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

How Sec-WebSocket-Accept is computed

  1. Concatenate the client's Sec-WebSocket-Key with the magic GUID 258EAFA5-E914-47DA-95CA-C5AB0DC85B11.
  2. Compute the SHA-1 hash of that string.
  3. Base64-encode the 20-byte hash.

That's it — the magic GUID exists so a generic HTTP server can't accidentally reply correctly to a WS handshake. Both sides know the constant; only a WebSocket-aware server will compute and echo it.

Validation

Reject the upgrade (400 Bad Request) if any of:

  • Method isn't GET
  • Upgrade header is missing or not websocket (case-insensitive)
  • Connection header doesn't include Upgrade
  • Sec-WebSocket-Key is missing
  • Sec-WebSocket-Version isn't 13

After the 101, the socket carries WebSocket frames: 2-14 byte header, masking key (client->server only), then the payload. The framing format is its own rabbit hole — but the handshake above is the gate.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…