· 2 min read
WebSocket on the standard library: what really happens under new WebSocket()
Why realtime-rooms has its own RFC 6455 layer, which protocol violations it checks, and why a library is still the better choice for production.
The WebSocket layer in realtime-rooms (internal/ws, about 530 lines) is written with the standard library only. The goal was educational: to see what hides under new WebSocket(...).
The handshake
It is a plain GET with Connection: Upgrade, Upgrade: websocket, version 13 and a 16-byte key (base64). The server answers 101 with Sec-WebSocket-Accept. Origin is checked too: the same host, a value from ALLOWED_ORIGINS, or no header for non-browser clients; otherwise 403.
Frames
The length is encoded in 7, 16 or 64 bits, and a non-minimal encoding is rejected. Client frames must be masked, server frames must not. Control frames are at most 125 bytes and are never fragmented. The size is checked from the header before any memory is allocated, so a huge frame cannot balloon the process.
What the tests check
The handshake example from the RFC, the masked-frame example, fragmentation with a ping in the middle, and 12 kinds of protocol violations, each verified by its close code.
An honest caveat
For production one normally uses a proven library: it has passed the Autobahn Test Suite, supports permessage-deflate and covers more edge cases. Autobahn was not run here and extensions are not supported. This is a learning layer, not a replacement for a library.