indexWebSocket Protocol from Scratch#websocket#rfc6455#protocol

WebSocket Protocol from Scratch

The centerpiece of this atlas: RFC 6455, implemented by hand in C, with no library standing between your code and the spec. After designing a protocol of your own, this is where the real standard's decisions stop looking arbitrary — the HTTP Upgrade handshake and the Sec-WebSocket-Accept computation (SHA-1 + base64 + the magic GUID), the complete frame format (the FIN bit, opcode, the masking requirement, and all three payload-length encodings), the control frames (ping, pong, close), message fragmentation across multiple frames, and the close handshake that ends a connection cleanly instead of just dropping it.

v2 of the chat migrates onto this implementation, verified against a real browser's native WebSocket client — not just your own C client talking to itself.

Planned notes

  • Reading RFC 6455 as a working document: which sections matter for a server, which for a client
  • The HTTP Upgrade handshake: request headers, Sec-WebSocket-Key, and why WebSocket rides in on HTTP/1.1 at all
  • Computing Sec-WebSocket-Accept: Sec-WebSocket-Key + the magic GUID, SHA-1, base64 — by hand, no crypto library shortcuts that skip the mechanism
  • The frame format bit by bit: FIN, RSV bits, opcode, the mask bit, and the payload-length encoding's three sizes (7-bit, 16-bit extended, 64-bit extended)
  • Client-to-server masking: why it's mandatory, how the masking key is applied, and the security reasoning behind it
  • Control frames: ping/pong for liveness, close for a clean shutdown, and their size/fragmentation restrictions
  • Message fragmentation: sending one logical message across multiple frames, and reassembling it correctly
  • The close handshake: sending and receiving a close frame, status codes, and the difference between a clean close and a dropped connection
  • Verifying your server against a real browser tab's new WebSocket(...) — the test that a self-talking client/server pair can't give you
  • Comparing your v1 custom protocol's design choices against what RFC 6455 actually chose, and why

Core sources

  • RFC 6455 (datatracker.ietf.org/doc/html/rfc6455) — the primary and mandatory source; read it directly.
  • MDN, "Writing WebSocket Servers" — a complementary implementation guide.
  • swss (C, RFC 6455, no dependencies) — a reference implementation for design comparison; never copy its code.

Connects to: Custom Binary Protocol · Client in C · Client in TypeScript