Nyx by Example

WebSocket

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.

Code

// WebSocket framing — build and parse frames (RFC 6455)

import "std/websocket"

fn main() -> int {
    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")

    let parsed: String = ws_parse(frame)
    print("parsed: " + parsed)

    let ws_key: String = "dGhlIHNhbXBsZSBub25jZQ=="
    let handshake: String = ws_handshake_response(ws_key)
    print("handshake response:")
    print(handshake)

    return 0
}

Output

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=

Explanation

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.

← Previous Next →

Source: examples/by-example/53-websocket.nx