Esc

WebSocket

moduleextensionSource
  • macOS: Everything works on macOS
  • Linux: Everything works on Linux
  • Windows: Everything works on Windows
  • Wasm: Everything works on Wasm
·since 0.36.1

#import "Extensions/WebSocket";

WebSocket (RFC 6455) framing and messages with bounded permessage-deflate (RFC 7692), plus a connection type for servers (ws_upgrade) and clients (ws_connect). The codec is sans-IO: feed it bytes with ws_parse and build frames with ws_frame. Event bytes belong to the codec until the next parse; release it with ws_free.

Example↗
#import "Extensions/WebSocket";

frame: [..] u8;
defer array_free(frame);
assert(ws_frame(*frame, .TEXT, cast([] u8) "hi").kind == .NONE);

codec := Ws_Codec.{ role = .CLIENT };
defer ws_free(*codec);
used, event := ws_parse(*codec, frame);
assert(used == frame.count && event.kind == .MESSAGE);
assert(event.data.count == 2);

Procedures#

General#

ws_parsesince 0.36.1Source
(c: *Ws_Codec, bytes: [] u8) -> (used: s64, event: Ws_Event)

Parses any input chunk, stopping at one message or control event. Example: used, event := ws_parse(*codec, bytes).

ws_framesince 0.36.1Source
(out: *[..] u8, opcode: Ws_Opcode, data: [] u8, final := true, masked := false, key: [4] u8 = .{}, compressed := false, options := Ws_Options.{}) -> Ws_Error

Appends one frame with an explicit masking key. Example: ws_frame(*out, .TEXT, cast([] u8) "hi"). Client transports must obtain a fresh unpredictable key for every call.

ws_deflatesince 0.36.1Source
(role: Ws_Role, settings: Ws_Deflate, data: [] u8, history: [] u8) -> [] u8

Compresses one message for sending as role, with the window that role negotiated (client_max_window_bits for a client, server_max_window_bits for a server). history is the sender's retained context, empty without it. The result is a sync-flushed raw deflate message that must be freed. Example: packed := ws_deflate(.CLIENT, codec.compression, text, .[]).

ws_freesince 0.36.1Source
(c: *Ws_Codec)

Releases codec buffers and resets all state. Example: defer ws_free(*codec).

Handshake#

(key: string) -> string

Computes RFC 6455's allocated accept value. Example: accept := ws_accept_key(key); free(accept).

ws_negotiatesince 0.36.1Source
(value: string, response := false) -> (Ws_Deflate, Ws_Error)

Negotiates a bounded extension header; response=true forbids offers without a window value. Example: compression, error := ws_negotiate("permessage-deflate; client_max_window_bits").

Connection#

ws_upgradesince 0.36.1Source
(request: *Http.Request, handler: Ws_Handler, data: *void = null, config := Ws_Config.{}) -> Http.Response

Validates an upgrade and returns a routed response. Example: return ws_upgrade(request, echo). The callback borrows the connection until it returns; config.protocols and data must outlive it.

ws_connectsince 0.36.1Source
(url: string, config := Ws_Config.{}, client: *Http.Client = null) -> (Ws_Connection, Ws_Error)

Connects on the calling Io fiber, sharing Http's transport and TLS configuration. Example: connection, error := ws_connect("wss://example.org/chat"); defer ws_dispose(*connection).

ws_readsince 0.36.1Source
(connection: *Ws_Connection) -> Ws_Event

Reads a message or close; answers pings automatically and ignores pongs. Example: event := ws_read(*connection); if event.kind == .MESSAGE consume(event.data).

ws_writesince 0.36.1Source
(connection: *Ws_Connection, data: [] u8, opcode := Ws_Opcode.TEXT) -> Ws_Error

Sends a complete text/binary message, fragmenting to max_frame_size, or a ping/pong. Example: error := ws_write(*connection, cast([] u8) "hello", .TEXT).

ws_closesince 0.36.1Source
(connection: *Ws_Connection, code: u16 = 1000, reason: string = "") -> Ws_Error

Sends close and waits for the peer under close_timeout, then releases the connection. Example: error := ws_close(*connection, 1000, "done"). Do not call beside another reader.

ws_disposesince 0.36.1Source
(connection: *Ws_Connection)

Aborts without a close handshake and releases owned buffers. Example: defer ws_dispose(*connection).

Types#

Ws_Roleenumsince 0.36.1Source

Which end a Ws_Codec is parsing for. A .SERVER codec reads frames from a client, which must be masked; a .CLIENT codec reads unmasked frames from a server.

Ws_Role :: enum {
    SERVER;
    CLIENT;
}
Ws_Opcodeenumsince 0.36.1Source

The kind of a frame, with the protocol's numeric values. Control frames (CLOSE, PING, PONG) are 8 and above.

Ws_Opcode :: enum u8 {
    CONTINUATION :: 0;
    TEXT :: 1;
    BINARY :: 2;
    CLOSE :: 8;
    PING :: 9;
    PONG :: 10;
}
Ws_Error_Kindenumsince 0.36.1Source

Why a WebSocket operation failed.

Ws_Error_Kind :: enum {
    NONE;
    PROTOCOL;
    UTF8;
    LIMIT;
    COMPRESSION;
    HANDSHAKE;
    TRANSPORT;
    TIMED_OUT;
    CLOSED;
}
Ws_Errorstructsince 0.36.1Source

The outcome of a WebSocket operation; kind is .NONE on success. message is static, offset is a byte position in the stream when known.

Ws_Error :: struct {
    kind: Ws_Error_Kind;
    message: string;
    offset: s64;
}
Ws_Optionsstructsince 0.36.1Source

Size limits for incoming data and for ws_frame. Exceeding one fails with .LIMIT.

Ws_Options :: struct {
    max_frame_size: s64 = 16 << 20;
    max_message_size: s64 = 64 << 20;
}
Ws_Deflatestructsince 0.36.1Source

The negotiated permessage-deflate settings. Parse an offer or response with ws_negotiate; the *_present flags record which window parameters were stated explicitly.

Ws_Deflate :: struct {
    enabled: bool;
    server_window_present: bool;
    client_window_present: bool;
    server_no_context_takeover: bool;
    client_no_context_takeover: bool;
    server_max_window_bits: int = 15;
    client_max_window_bits: int = 15;
}
Ws_Eventstructsince 0.36.1Source

One event. data is a borrowed view of the message or control payload, valid until the next parse. opcode tells text from binary; code is the status of a close frame.

Ws_Event :: struct {
    kind: Ws_Event_Kind;
    opcode: Ws_Opcode;
    data: [] u8;
    code: u16;
    error: Ws_Error;
}
Ws_Codecstructsince 0.36.1Source

An incremental frame parser for one direction of a connection. Set role, options and compression before the first ws_parse; the other fields are its state. Release it with ws_free.

Ws_Codec :: struct {
    role: Ws_Role;
    options: Ws_Options;
    compression: Ws_Deflate;
    header: [14] u8;
    header_count: int;
    header_size: int = 2;
    length: s64;
    received: s64;
    offset: s64;
    opcode: Ws_Opcode;
    message_opcode: Ws_Opcode;
    final: bool;
    masked: bool;
    compressed: bool;
    fragmented: bool;
    delivered: bool;
    closed: bool;
    utf_remaining: int;
    utf_low: u8 = 0x80;
    utf_high: u8 = 0xBF;
    message: [..] u8;
    control: [..] u8;
    dictionary: [..] u8;
    error: Ws_Error;
}
Ws_Configstructsince 0.36.1Source

Settings for ws_upgrade and ws_connect. protocols lists the subprotocols to offer or accept in preference order and must outlive the connection. Timeouts are in milliseconds; 0 or less means none.

Ws_Config :: struct {
    limits: Ws_Options;
    compression := true;
    protocols: [] string;
    handshake_timeout: s64 = 30000;
    read_timeout: s64;
    write_timeout: s64 = 30000;
    close_timeout: s64 = 5000;
}
Ws_Connectionstructsince 0.36.1Source

Connection values must not be copied after first use. One reader and one writer may run concurrently.

Ws_Connection :: struct {
    codec: Ws_Codec;
    config: Ws_Config;
    protocol: string;
    link: Http.Link;
    pending: [] u8;
    initial: [] u8;
    buffer: [16384] u8;
    write_lock: Io.Fiber_Mutex;
    dictionary: [..] u8;
    close_sent: bool;
    owned: bool;
    disposed: bool;
}
Ws_Handlertypesince 0.36.1Source
:: #type (connection: *Ws_Connection, data: *void)

Runs a server connection after a successful ws_upgrade. The connection is borrowed until it returns; data is what you passed to ws_upgrade.