Module std::net::websocket

WebSocket client and server for bidirectional communication.

Provides blocking WebSocket connections that can send and receive text messages. Both client and server connections use the same Conn type, so the send/receive API is identical in both directions.

Client example

import std.net.websocket;

fn main() {
    match websocket.connect("ws://localhost:8080/ws") {
        .Ok(ws) => {
            ws.send_text("hello");
            let msg = ws.recv();
            msg.close();
            ws.close();
        }
        .Err(_err) => {
            println(websocket.last_error());
        }
    }
}

Server example

import std.net.websocket;

fn main() {
    match websocket.listen("0.0.0.0:8080") {
        .Ok(server) => {
            let conn = server.accept();
            let msg = conn.recv();
            conn.send_text("got it");
            conn.close();
            server.close();
        }
        .Err(_err) => {
            println(websocket.last_error());
        }
    }
}

Contents

Functions

Function last_error

pub fn last_error() -> string

Return the detail of this actor's most recent WebSocket failure.

Returns the empty string when the last call succeeded. Call it immediately after an Err for the precise, non-secret reason.

Function connect

pub fn connect(url: string) -> Result<Conn, net.NetError>

Open a WebSocket connection to the given URL (client).

Returns Err(net.NetError) when the connection or the WebSocket handshake fails. Use websocket.last_error() for the precise detail.

Examples

import std.net;
import std.net.websocket;

fn main() {
    match websocket.connect("ws://127.0.0.1:9001/") {
        .Ok(conn) => conn.close(),
        .Err(_) => println(f"connect failed"),
    }
}

Function listen

pub fn listen(addr: string) -> Result<Server, net.NetError>

Start a WebSocket server listening on the given address.

Returns Err(net.NetError) when the address cannot be bound. Use websocket.last_error() for the precise detail.

Examples

import std.net;
import std.net.websocket;

fn main() {
    match websocket.listen("127.0.0.1:0") {
        .Ok(server) => server.close(),
        .Err(_) => println(f"listen failed"),
    }
}

Types

Struct Conn

An open WebSocket connection handle.

Created by calling websocket.connect(url), which returns Err when the connection or handshake fails. Use send_text() to send messages and recv() to receive them.

Struct Message

An incoming WebSocket message handle.

Obtained from conn.recv(). Messages close automatically at scope exit; call close() to release one early.

Struct Server

A WebSocket server listening for incoming connections.

Created by calling websocket.listen(addr), which returns Err when the address cannot be bound. Use accept() to wait for the next client connection.

Traits

Trait ConnMethods

Methods available on a WebSocket Conn.

Methods

fn send_text(self: Self, msg: string) -> i64

Send a text message over the connection. Return 0 on success.

fn try_send_text(self: Self, msg: string) -> Result<(), net.NetError>

Send a text message over the connection.

fn recv(self: Self) -> Message

Block until a message is received and return it.

fn recv_timeout(self: Self, deadline_ms: i64) -> Result<Message, net.NetError>

Receive a message with a per-call deadline.

deadline_ms <= 0 disables the deadline and behaves like recv. Returns Err(NetError.TimedOut(0)) on deadline expiry. On other failures returns Err(NetError.Other(0)) (WebSocket errors carry no OS errno channel).

fn attach(self: Self, handler: WebSocketHandler)

Attach this connection to an actor (Erlang-style active mode). The runtime reads frames in a background thread and delivers them as actor messages. The connection remains the caller's resource; attach transfers read authority only. Outbound sends and close remain valid while the reader retains the transport's shared inner state.

handler is the actor that will receive on_message and on_close. The compiler synthesises both protocol message IDs from the concrete actor type behind the handle.

Trait MessageMethods

Methods available on a WebSocket Message.

Methods

fn msg_type(self: Self) -> i32

Get the message type (0=text, 1=binary, 2=ping, 3=pong, 4=close, -1=error).

fn text(self: Self) -> string

Extract the text content of a text message.

Trait ServerMethods

Methods available on a WebSocket Server.

Methods

fn accept(self: Self) -> Conn

Accept the next WebSocket connection. Blocks until a client connects and completes the handshake.

fn port(self: Self) -> i64

Get the port the server is listening on.

Trait WebSocketHandler

Trait for actors that handle WebSocket connections.

Implement this on an actor and call conn.attach(actor) to have the runtime deliver frames as actor messages. The actor never calls recv() โ€” the runtime reads in a background thread.

Example

import std.net.websocket;

actor Echo {
    let conn: websocket.Conn;
    receive fn on_message(text: string) {
        conn.send_text("echo: " + text);
    }
    receive fn on_close() {
        println("disconnected");
    }
}

Methods

fn on_message(text: string)

Called when a text frame arrives from the client.

fn on_close()

Called when the connection closes or errors.