std/websocket implements RFC 6455 WebSocket framing. ws_frame wraps a text payload into a WebSocket frame, ws_parse extracts the payload from a frame, and ws_handshake_response generates the HTTP 101 Upgrade response required to establish a WebSocket connection.
53-websocket.nxSource →
// WebSocket framing — build and parse frames (RFC 6455) // Framing WebSocket — construir y parsear frames import "std/websocket" fn main() -> int { // Build a WebSocket text frame let payload: String = "Hello, WebSocket!" let frame: String = ws_frame(payload) print("frame length: " + int_to_string(frame.length()) + " bytes") print("payload length: " + int_to_string(payload.length()) + " bytes") // Parse a frame back to its payload let parsed: String = ws_parse(frame) print("parsed: " + parsed) // Generate a handshake response for a given Sec-WebSocket-Key let ws_key: String = "dGhlIHNhbXBsZSBub25jZQ==" let handshake: String = ws_handshake_response(ws_key) print("handshake response:") print(handshake) return 0 }
Outputstdout
frame length: 19 bytes payload length: 17 bytes parsed: Hello, WebSocket! handshake response: HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
How it works
A WebSocket frame has a 2-byte header (FIN bit, opcode, payload length) followed by the payload. ws_frame creates a text frame (opcode 0x81) with the correct length encoding. ws_parse reads the header and extracts the payload bytes.
The handshake response computes the Sec-WebSocket-Accept header by concatenating the client's key with a magic GUID and computing SHA-1. This is handled by runtime/websocket.c.