Skip to content

std::websocket

WebSockets (RFC 6455): one long-lived connection on which the client and the server each send messages whenever they like.

A server accepts the handshake in a handler with websocket.accept, which returns the 101 Switching Protocols response and runs its function over the connection once it is sent, on the request’s task, for as long as the connection lives. The connection closes when the function returns:

fn echo(request: Request) -> Response
    websocket.accept(request, fn ws ->
        _ = WebSocket.each(ws, fn message ->
            _ = WebSocket.send(ws, message)
        end)
    end)
end

A client connects with websocket.connect to a ws:// or wss:// URL. Either end receives with WebSocket.receive, which returns Ok(None) once the peer has closed cleanly, and sends with WebSocket.send or send_text. Any task may send on a connection at any time, as an actor broadcasting to many does: sends are taken one at a time. One task receives. A ping is answered with a pong while a task is receiving.

accept checks the Origin a browser sends: a page on another host is refused with 403 unless its origin is in allowed_origins. A request with no Origin is not from a browser and passes. A message over max_message_size, 1 MiB unless set, closes the connection with 1009; a text message that is not UTF-8 closes it with 1007.

Middleware sees the 101 response the handler returns, when the handler returns it: log_requests logs the handshake, compress leaves a 1xx response alone, timeout bounds only the handler’s return, and limit_body limits a body the handshake does not have. Server.request_timeout is a deadline for the request’s whole task, the connection’s life included, so a server that serves WebSockets leaves it unset or sets it longer than any connection. When the program shuts down, each connection is closed with 1001.

Import with import std::websocket.

enum Message
    Text String
    Binary Bytes
end

One message: text, which is UTF-8, or bytes.

impl Debug for Message

fn inspect(value: Message) -> String

impl Debug.inspect

impl Equatable for Message

fn equal(a: Message, b: Message) -> Bool

impl Equatable.equal

enum Error
    Handshake { status: Status, reason: String }
    Protocol { code: Int, reason: String }
    Closed { code: Int, reason: String }
    Timeout
    Invalid { reason: String }
    Network { error: net.Error }
    InvalidUrl { url: String, reason: String }
end

Why a WebSocket could not be opened or used. A close code is RFC 6455’s: 1000 normal, 1001 going away, 1002 a protocol error, 1006 no close frame, 1007 bad data, 1008 a policy violation, 1009 too big, 1011 a server error, and 3000 to 4999 for libraries and applications.

Variants

  • Handshake

    The server did not accept the handshake: its status, and why.

  • Protocol

    The peer broke the protocol or sent a message over the limit, so the connection was closed with code.

  • Closed

    The connection ended: the peer closed it with code, one other than 1000 or 1001, or it ended with no close frame (1006), or it was closed already.

  • Timeout

    No frame arrived within the idle timeout.

  • Invalid

    A value the protocol cannot send: a close code, a text that is not UTF-8, a ping over 125 bytes.

  • Network

    Connecting failed.

  • InvalidUrl

    A URL that is not ws:// or wss://.

impl Display for Error

fn to_string(error: Error) -> String

impl Display.to_string

import std::websocket.Error

assert "${Error.Protocol{code: 1009, reason: "a message over 10 bytes"}}"
    == "websocket closed with 1009: a message over 10 bytes"

impl Debug for Error

fn inspect(value: Error) -> String

impl Debug.inspect

impl Equatable for Error

fn equal(a: Error, b: Error) -> Bool

impl Equatable.equal

struct AcceptOptions
    allowed_origins: List<Origin> = []
    protocols: List<String> = []
    headers: Headers = Headers[]
    max_message_size: Int = 1_048_576
    ping_interval: Maybe<Duration> = None
    idle_timeout: Maybe<Duration> = None
end

How accept takes a handshake.

impl Debug for AcceptOptions

fn inspect(value: AcceptOptions) -> String

impl Debug.inspect

struct ConnectOptions
    headers: Headers = Headers[]
    protocols: List<String> = []
    max_message_size: Int = 1_048_576
    ping_interval: Maybe<Duration> = None
    idle_timeout: Maybe<Duration> = None
    tls: ClientConfig = ClientConfig{}
    dial: DialOptions = DialOptions{}
end

How connect opens a connection.

impl Debug for ConnectOptions

fn inspect(value: ConnectOptions) -> String

impl Debug.inspect

struct WebSocket

opaque — construction surface is private to its defining module

An open WebSocket connection, either end.

fn receive(ws: WebSocket) -> Result<Maybe<Message>, Error>

type function on WebSocket

The next message, or Ok(None) once the peer has closed with 1000 or 1001 or no code, and on every call after that. It waits until a message comes, and stops when the task is cancelled.

fn each(ws: WebSocket, handle: (Message) -> Unit) -> Result<Unit, Error>

type function on WebSocket

Hands each message to handle as it arrives, until the peer closes cleanly (Ok) or the connection fails.

import std::http.{Method, Request, Response}
import std::http::testing
import std::websocket.{self, Message, WebSocket}

echo = fn request: Request ->
    websocket.accept(request, fn ws ->
        _ = WebSocket.each(ws, fn message ->
            _ = WebSocket.send(ws, message)
        end)
    end)
end

got = testing.open_websocket(echo, "/echo", fn ws ->
    _ = WebSocket.send_text(ws, "hello")
    _ = WebSocket.send(ws, Message.Binary(String.to_bytes("raw")))
    [WebSocket.receive(ws), WebSocket.receive(ws)]
end)

assert Ok(replies) = got

assert replies == [
    Ok(Some(Message.Text("hello"))),
    Ok(Some(Message.Binary(String.to_bytes("raw")))),
]
fn send(ws: WebSocket, message: Message) -> Result<Unit, Error>

type function on WebSocket

Sends message as one frame. Sends from several tasks go one at a time.

fn send_text(ws: WebSocket, text: String) -> Result<Unit, Error>

type function on WebSocket

Sends text as a text message.

fn ping(ws: WebSocket, data: Bytes = String.to_bytes("")) -> Result<Unit, Error>

type function on WebSocket

Sends a ping carrying data, at most 125 bytes; the peer answers with a pong, which receive takes on its way.

fn close(ws: WebSocket, code: Int = 1000, reason: String = "") -> Result<Unit, Error>

type function on WebSocket

Closes the connection with code and reason, at most 123 bytes: sends a close frame, waits up to five seconds for the peer’s, then closes. Closing a closed connection does nothing.

import std::http.Request
import std::http::testing
import std::websocket.{self, Error, WebSocket}

leave = fn request: Request ->
    websocket.accept(request, fn ws ->
        _ = WebSocket.close(ws, 4000, "done here")
    end)
end

got = testing.open_websocket(leave, "/", fn ws -> WebSocket.receive(ws))
assert Ok(received) = got
assert received == Err(Error.Closed{code: 4000, reason: "done here"})
fn protocol(ws: WebSocket) -> Maybe<String>

type function on WebSocket

The subprotocol the two ends agreed on, if any.

fn id(ws: WebSocket) -> Int

type function on WebSocket

A number no other WebSocket of the program has, for keeping connections in a Map.

fn over(conn: Connection, client: Bool, protocol: Maybe<String> = None, max_message_size: Int = 1_048_576) -> WebSocket

type function on WebSocket

A WebSocket over conn, whose handshake was done some other way; client says which end this is, since a client masks its frames.

impl Debug for WebSocket

fn inspect(value: WebSocket) -> String

impl Debug.inspect

fn accept(request: Request, options: AcceptOptions = AcceptOptions{}, on_open: (WebSocket) -> Unit) -> Response

Accepts request’s WebSocket handshake: the 101 response, which runs on_open over the connection once it is sent and closes the connection with 1000 when on_open returns. A request that is not a handshake gets 426 Upgrade Required (or 405 for a method other than GET, or 400 for a bad key), and one from a page on another origin gets 403.

import std::http.{Method, Origin, Request, Response, Status}
import std::http::testing
import std::websocket.{self, AcceptOptions, WebSocket}

chat = fn request: Request ->
    websocket.accept(request, AcceptOptions{protocols: ["chat.v2", "chat.v1"]}, fn ws ->
        _ = WebSocket.send_text(ws, "welcome")
    end)
end

offered = Headers[("Sec-WebSocket-Protocol", "chat.v1, chat.v2")]

got = testing.open_websocket(chat, "/chat", offered, fn ws ->
    (WebSocket.protocol(ws), WebSocket.receive(ws), WebSocket.receive(ws))
end)

assert Ok(seen) = got
assert seen == (Some("chat.v2"), Ok(Some(websocket.Message.Text("welcome"))), Ok(None))

plain = chat(testing.request(Method.Get, "/chat"))
assert plain.status == Status.upgrade_required

elsewhere = Headers[("Origin", "https://evil.example")]
assert Err(refused) = testing.open_websocket(chat, "/chat", elsewhere, fn _ -> Unit)
assert refused.status == Status.forbidden

own = Headers[("Origin", "http://example.com")]
assert testing.open_websocket(chat, "/chat", own, fn _ -> Unit) |> Result.is_ok()
fn is_upgrade(request: Request) -> Bool

Whether request asks to upgrade to a WebSocket, for a handler that serves a page and a socket at one path.

import std::http.{Method, Request}
import std::http::testing
import std::websocket

r = testing.request(Method.Get, "/")
refute websocket.is_upgrade(r)
assert websocket.is_upgrade({..r, headers: Headers[("Upgrade", "WebSocket")]})
fn connect(url: Url, options: ConnectOptions = ConnectOptions{}) -> Result<WebSocket, Error>

Connects to url, ws:// or wss://, and runs the handshake. An Error.Handshake holds the status of a server that refused.

import std::http.{Request, Response, Status}
import std::http::testing
import std::url.Url
import std::websocket.{self, Error, Message, WebSocket}

echo = fn request: Request ->
    websocket.accept(request, fn ws ->
        _ = WebSocket.each(ws, fn message ->
            _ = WebSocket.send(ws, message)
        end)
    end)
end

said = testing.with_server(echo, fn server ->
    ws = websocket.connect(Url.parse("ws://${server.url.host}/echo")!)!
    _ = WebSocket.send_text(ws, "over a socket")
    reply = WebSocket.receive(ws)
    _ = WebSocket.close(ws)
    reply
end)

assert said == Ok(Some(Message.Text("over a socket")))

page = fn _: Request -> Response{status: Status.not_found}

refused = testing.with_server(page, fn server ->
    websocket.connect(Url.parse("ws://${server.url.host}/")!) |> Result.map(fn _ -> Unit)
end)

assert Err(Error.Handshake{status:, reason: _}) = refused
assert status == Status.not_found
assert websocket.connect(Url"https://example.com") is Err(Error.InvalidUrl{url: _, reason: _})

Not run here: this example opens network connections and serves network requests, which a browser cannot do. nomi test runs it.