#WebSocket API for MoonBit Async Library

    This module provides RFC 6455-compliant WebSocket client and server support for moonbitlang/core/async.

    #Features

    • WebSocket server with support for integration into a normal HTTP server
    • WebSocket client with support for TLS and proxy

    #Quick Start

    #WebSocket server

    // A simple WebSocket echo server that listen on path `/ws`,
    // and reply clients with whatever they send.

    ///|
    #cfg(any(target="native", target="wasm"))
    async fn websocket_echo_server(addr : @socket.Addr) -> Unit {
    let server = @http.Server(addr, reuse_addr=true)
    // WebSocket server are built on top of a HTTP server.
    // This allows mixing WebSocket and HTTP in a single server.
    server.run_forever((request, conn) => {
    guard request.path is "/ws" else { conn.send_response(404, "NotFound") }
    let ws = @websocket.from_http_server(request, conn)
    defer ws.close()
    for ;; {
    // Receive a new message using `ws.recv()`
    // WebSocket message can be very long,
    // so `ws.recv()` does not read the full message into memory.
    // Instead, it returns a `@websocket.Message` type,
    // whose content can be read lazily via `@io.BinaryReader`.
    let msg = ws.recv()
    // Reply the client with the message we just received.
    // `msg.kind` is either `Text` (UTF-8 encoded text message)
    // or `Binary` (plain binary message).
    //
    // Sending message can also be performed lazily.
    // `.start_message(message_kind)` begins a new message,
    // after which message content can be written lazily to the WebSocket tunnel.
    // After all message content is written,
    // `.end_message()` should be called to terminate the message.
    // Fragmentation of message will be performed automatically.
    ws..start_message(msg.kind)..write_reader(msg).end_message()
    }
    })
    }

    #WebSocket client

    ///|
    #cfg(any(target="native", target="wasm"))
    async test "WebSocket client example" {
    @async.with_task_group(group => {
    let port = 8340
    let addr = @socket.Addr::parse("127.0.0.1:\{port}")
    group.spawn_bg(no_wait=true, () => websocket_echo_server(addr))

    @async.sleep(100) // wait for the server to start

    // Create a new client via `@websocket.connect`.
    // TLs encrypted WebSocket tunnel can be created via `wss://` URL.
    let ws = @websocket.connect("ws://127.0.0.1:\{port}/ws")
    defer ws.close()
    // convenient helper for sending small text message
    ws.send_text("abcd")
    inspect(ws.recv().text.read_all(), content="abcd")
    // gracefully terminate the WebSocket tunnel
    ws.send_close()
    })
    }

    #API Reference

    #Conn

    The type @websocket.Conn represents a WebSocket tunnel. It can be created in the following three ways:

    • @websocket.connect(url : String, headers?, proxy?): connect to url via HTTP, perform WebSocket handshake and establish a new tunnel. If the url starts with ws://, the tunnel will be unencrypted, and handshake is performed via plain HTTP. If the url starts with wss://, a TLS encrypted tunnel will be created, and handshake is performed via HTTPS. The optional argument headers can be used to specify addition headers in the handshake. The optional argument proxy can be used to specify a HTTP(s) proxy for the tunnel.
    • @websocket.from_http_client(client : @http.Client, path: String): similar to @websocket.connect, but create the WebSocket tunnel using an existing http client.
    • @websocket.from_http_server(request : @http.Request, conn : @http.ServerConnection): process a WebSocket handshake request request from a client, and upgrade the HTTP server connection conn to a WebSocket tunnel.

    After successfully establishing a WebSocket tunnel, the following API can be used to do things with the tunnel:

    • recv() -> Message: receive a new message from the tunnel. The kind of the message can be retrieved via msg.kind. recv() will not actually receive the content of the message, the content of the message should be obtained by reading from the Message type.
    • send_text(text : StringView): send a new text message
    • send_binary(data : BytesView): send a new binary message
    • start_message(kind : MessageKind): start a new message of kind kind. The content of the new message can be written to the WebSocket tunnel through its @io.BinaryWriter API, or through .text as @io.TextWriter
    • end_message(): terminate current message created via start_message(), flush remaining content of message to the server
    • send_close(): gracefully terminate the WebSocket tunnel by sending a CLOSE frame. This method should only be used when no network or protocol error occurs.
    • close(): dispose a WebSocket tunnel, release related resource. The underlying HTTP connection will be closed as well.
    • impl @io.BinaryWriter for Conn: write binary content to the message currently being sent, created via .start_message()
    • ping(): actively send a WebSocket PING message and wait for corresponding PONG reply. .ping() can be called inside another message being sent. However, .ping() must be called when there is another task receiving message from the tunnel in parallel, otherwise the PONG reply can not be fetched, and .ping() will hang forever.

    #Message

    A single message received from a WebSocket tunnel.

    • field kind: the kind of the message
    • impl @io.BinaryReader for Message: read binary content of the message. For example, content of the whole message can be obtained via .read_all()

    #CloseCode

    WebSocket close code.

    ///|
    #derive(Debug, Eq)
    pub(all) enum CloseCode {
    Normal // 1000
    GoingAway // 1001
    ProtocolError // 1002
    UnsupportedData // 1003
    Abnormal // 1006
    InvalidFramePayload // 1007
    PolicyViolation // 1008
    MessageTooBig // 1009
    MissingExtension // 1010
    InternalError // 1011
    Other(UInt16)
    }

    #Error Types

    #WebSocketError

    ///|
    #derive(Debug)
    suberror WebSocketError {
    // Connection was closed with specific code.
    // with an optional message for close reason.
    ConnectionClosed(CloseCode, String?)
    InvalidHandshake(String) // Handshake failed with detailed reason
    ProtocolError // Malformed frame
    }

    WebSocketError

    pub suberror WebSocketError {
    ConnectionClosed(CloseCode, String?)
    InvalidHandshake(String)
    HandshakeRejected(String,
    ResponseHeader
    )
    ProtocolError(String)
    } derive(
    Debug
    )

    Error from a WebSocket connection

    CloseCode

    pub(all) enum CloseCode {
    Normal
    GoingAway
    ProtocolError
    UnsupportedData
    Abnormal
    InvalidFramePayload
    PolicyViolation
    MessageTooBig
    MissingExtension
    InternalError
    Other(UInt16)
    } derive(Eq,
    Debug
    )

    WebSocket close status codes

    CloseCode::equal

    fn CloseCode::equal(CloseCode, CloseCode) -> Bool
    automatically derived

    Conn

    pub struct Conn {
    text :
    Utf8Writer

    // private fields
    }

    A WebSocket connection

    Conn::close

    fn Conn::close(self : Conn) -> Unit

    Close a WebSocket connection. The underlying HTTP connection will be closed as well.

    Conn::connect

    #as_free_fn
    async fn Conn::connect(url : String, headers? : Map[
    CaseInsensitiveString
    , String], proxy? :
    Proxy
    ) -> Conn

    Connect to a WebSocket server via the given URL. The protocol of the URL must be either ws (for unencrypted WebSocket connection) or wss (for TLS encrypted WebSocket connection).

    Extra headers during the WebSocket handshake can be specified via extra_headers. Some headers are reserved for the WebSocket protocol and must NOT be set in extra_headers:

    • those headers set by @http.ClientConnection, see @http.ClientConnection(..)
    • Connection, Upgrade
    • Sec-WebSocket-Key, Sec-WebSocket,Version

    If proxy is present, the websocket client will tunnel traffic through the proxy. See @http.ClientConnection(..) for more details.

    Example:
    let ws = Conn::connect("ws://example.com/endpoint")

    Conn::end_message

    async fn Conn::end_message(self : Conn) -> Unit

    End the message currently being sent, flush all buffered data and tell the server the termination of current message.

    end_message must be called after the start_message.

    Conn::flush_partial_data

    async fn Conn::flush_partial_data(self : Conn) -> Unit

    Flush all partial data and ensure they are delivered immediately. For writer transformers such as gzip writer, the underlying transport will be flushed as well. The flush is only best-effort: underlying implementation may choose to still buffer some data.

    flush_partial_data IS NOT used to ensure stream integrity: stream termination such as @tls.Tls::shutdown() is a protocol-specific operation. The only purpose of flush_partial_data is to ensure timely delivery of partial data. If the user only cares about eventual integrity of data, flush_partial_data is always UNNECESSARY.

    flush_partial_data mainly deal with userland buffering. It does not, for example, synchronize data to disk for a file system writer.

    Conn::from_http_client

    #as_free_fn
    async fn Conn::from_http_client(conn :
    ClientConnection
    , path : StringView, extra_headers? : Map[
    CaseInsensitiveString
    , String]) -> Conn

    Create a WebSocket tunnel from an existing HTTP client. The HTTP client must be in a clean state (i.e. not in the middle of a request). A WebSocket handshake will be sent to path via the HTTP client. If the handshake succeeds, a WebSocket tunnel will be established and returned.

    The ownership of the HTTP client will be transferred to this function. So caller must not use the client anymore, nor close it.

    Extra headers during the WebSocket handshake can be specified via extra_headers. Some headers are reserved for the WebSocket protocol and must NOT be set in extra_headers:

    • those headers set by @http.ClientConnection, see @http.ClientConnection(..)
    • Connection, Upgrade
    • Sec-WebSocket-Key, Sec-WebSocket,Version

    Conn::from_http_server

    Handle a WebSocket handshake request and convert an existing HTTP server connection to a WebSocket tunnel.

    • request: the WebSocket handshake request
    • conn: the HTTP server connection

    If the handshake succeeds, a new WebSocket tunnel will be created and returned.

    The ownership of conn will be transferred to @websocket.ServerConnection::from_http, so the user must NOT use or close the HTTP server connection anymore.

    Conn::ping

    async fn Conn::ping(self : Conn, msg? : BytesView) -> Unit

    Send a PING frame to the peer, and wait for PONG reply. If msg is provided, its content will become the body of the PING message. Otherwise, ping() automatically generate random bytes as message body.

    The PONG reply may not come immediately. In particular, it may arrive after several other messages already on the wire. To avoid data loss and race condition, .ping() itself will not wait for the PONG reply directly. User must receive data from the same WebSocket connection somewhere else, in order to get the PONG reply of a PING request. Calling .ping() without another task running .recv() on parallel WILL RESULT IN DEAD LOCK.

    If a PING request with the same message body is still waiting for reply, .ping() will fail immediately with error.

    Conn::recv

    async fn Conn::recv(self : Conn) -> Message

    Receive a new message from a WebSocket connection. Only the header of the message will be received, actual body of the message can be read streamingly through the returned message object.

    Conn::send_binary

    async fn Conn::send_binary(self : Conn, data : BytesView) -> Unit

    Convenient helper for sending a single binary message. To send large message lazily, see start_message.

    Conn::send_close

    async fn Conn::send_close(self : Conn, code? : CloseCode, reason? : String) -> Unit

    Initiating the connection closing process of WebSocket. Note that send_close merely performs closing at WebSocket protocol level, so:

    • Conn::close should be called anyway, even if send_close is called
    • Conn::send_close should only be called when everything goes well. For example it should NOT be called when protocol error or network error occurs.

    Conn::send_text

    async fn Conn::send_text(self : Conn, text : StringView) -> Unit

    Convenient helper for sending a single text message. To send large message lazily, see start_message.

    Conn::start_message

    fn Conn::start_message(self : Conn, kind : MessageKind) -> Unit

    Start sending a new message to the server. The content can then be sent through self as an @io.BinaryWriter, or through self.text as an @io.TextWriter. end_message must be explicitly called to terminate the message.

    Writing message content is buffered. To ensure immediate delivery of data, split them into multiple messages, and use end_message to ensure data is actually sent to the server.

    start_message must NOT be called before the last message ends.

    Conn::write

    async fn Conn::write(self : Conn, data : BytesView) -> Unit raise
    WriterError

    writer.write(data) writes a chunk of data into the writer. write will ensure that all content of data has been written before returning. However, write only guarantees that all data is committed to the underlying writer object; it does not guarantee writer-specific properties, such as written data being flushed to persistent storage for a file stream.

    Conn::write_reader

    async fn Conn::write_reader(self : Conn, reader : &
    BinaryReader
    ) -> Unit

    writer.write_reader(reader) continuously reads from input stream reader and writes all its content to writer until EOF is reached.

    write_reader only raises two kinds of error: @io.ReaderError from the reader, or @io.WriterError from the writer.

    Message

    pub struct Message {
    kind : MessageKind
    text :
    Utf8Reader

    // private fields
    }

    A message received from a WebSocket tunnel

    Message::drop_all

    async fn Message::drop_all(self : Message) -> Int64 raise
    ReaderError

    Drop all remaining content from a binary reader, until EOF is reached.

    Message::drop_exactly

    async fn Message::drop_exactly(self : Message, len : Int) -> Unit raise
    ReaderError

    reader.drop_exactly(len) drops exactly len bytes from the reader. drop_exactly waits until enough bytes are available. If EOF is reached before enough data is dropped, UnexpectedEof will be raised.

    Message::peek

    async fn Message::peek(self : Message) -> BytesView? raise
    ReaderError

    reader.peek() fetches and returns a chunk of data from the reader. The returned data will not get consumed from the reader: other reader API can still fetch them later.

    The chunk returned by reader.peek() is a copy-free slice of the reader's internal buffer, and its content will be overwritten by subsequent reader operations. So caller of peek MUST NOT use the returned slice after any other BinaryReader operation is invoked on the same reader. If the data need to be kept persistent, copy it via .to_owned().

    The returned chunk will contain at least one byte. If EOF is reached before any data is fetched, None will be returned.

    reader.peek() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.peek() is cancelled, no data will be lost.

    Message::peek_at_least

    async fn Message::peek_at_least(self : Message, min_len : Int) -> BytesView raise
    ReaderError

    reader.peek_at_least(min_len) fetches and returns a chunk containing at least min_len bytes without consuming it. The returned chunk may be larger than min_len.

    The returned view is valid only until another operation is invoked on the same reader. Use .to_owned() to keep the data persistently.

    If EOF is reached before enough data is fetched, UnexpectedEof will be raised. Any shorter trailing data remains buffered and can be fetched by a later reader operation.

    reader.peek_at_least() is cancellation safe as long as the underlying reader implementation is cancellation safe. When it is cancelled, no data will be lost.

    Message::peek_exactly

    async fn Message::peek_exactly(self : Message, len : Int) -> BytesView raise
    ReaderError

    reader.peek_exactly(len) fetches exactly len bytes from the reader. It will wait until enough number of bytes is available. The returned data will not get consumed from the reader: other reader API can still fetch them later.

    The chunk returned by reader.peek_exactly() is a copy-free slice of the reader's internal buffer, and its content will be overwritten by subsequent reader operations. So caller of peek MUST NOT use the returned slice after any other BinaryReader operation is invoked on the same reader. If the data need to be kept persistent, copy it via .to_owned().

    If EOF is reached before enough data is read, UnexpectedEof will be raised. In this case remaining data remain buffered, and can be fetched by other reader operations later.

    reader.peek_exactly() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.peek_exactly() is cancelled, no data will be lost.

    Message::peek_until

    async fn Message::peek_until(self : Message, pattern : BytesView, include_delimiter? : Bool) -> BytesView? raise
    ReaderError

    reader.peek_until(pat, include_delimiter? : Bool = false) fetches content from reader until the byte string pat is found in the reader stream. The returned data will not get consumed from the reader: other reader API can still fetch them later.

    The chunk returned by reader.peek_until() is a copy-free slice of the reader's internal buffer, and its content will be overwritten by subsequent reader operations. So caller of peek MUST NOT use the returned slice after any other BinaryReader operation is invoked on the same reader. If the data need to be kept persistent, copy it via .to_owned().

    If pat is found in the input stream, content before that occurrence is returned. If include_delimiter is true, pat itself is included at the end of the result. The returned data may be empty in this case if include_delimiter is false.

    EOF is implicitly treated as a delimiter by reader.peek_until(). If pat is not found in the input stream when EOF is reached, trailing data before EOF will be returned (or None if there is no trailing data). In this case, the returned data contains no trailing delimiter even if include_delimiter=true. This can be used to detect the presence of trailing delimiter in the input stream.

    reader.peek_until() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.peek_until() is cancelled, no data will be lost.

    Message::read

    reader.read() fetches and returns a chunk of data from the reader. It will return as fast as possible when new data become available.

    The returned chunk will contain at least one byte. If EOF is reached before any data is fetched, None will be returned.

    reader.read() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.read() is cancelled, no data will be lost.

    Message::read_all

    async fn Message::read_all(self : Message) -> Bytes raise
    ReaderError

    Read all remaining content from a binary reader, until EOF is reached.

    Message::read_at_least

    async fn Message::read_at_least(self : Message, min_len : Int) -> Bytes raise
    ReaderError

    reader.read_at_least(min_len) fetches and returns an owned chunk containing at least min_len bytes. The returned chunk may be larger than min_len.

    If EOF is reached before enough data is fetched, UnexpectedEof will be raised. Any shorter trailing data remains buffered and can be fetched through another reader operation later.

    reader.read_at_least() is cancellation safe as long as the underlying reader implementation is cancellation safe. When it is cancelled, no data will be lost.

    Message::read_exactly

    async fn Message::read_exactly(self : Message, len : Int) -> Bytes raise
    ReaderError

    reader.read_exactly(len) reads exactly len bytes from the reader. It will wait until enough number of bytes is available. If EOF is reached before enough data is read, UnexpectedEof will be raised.

    Message::read_into

    async fn Message::read_into(self : Message, dst : MutArrayView[Byte]) -> Int raise
    ReaderError

    reader.read_into(dst) reads at most dst.length() bytes from the reader into dst. The number of bytes actually read is returned. Note that the return value may be smaller than dst.length() if not enough data is immediately available. If EOF is reached and no more data is available, zero will be returned.

    Message::read_until

    async fn Message::read_until(self : Message, pattern : BytesView, include_delimiter? : Bool) -> Bytes? raise
    ReaderError

    reader.read_until(pat, include_delimiter? : Bool = false) reads content from reader until the byte string pat is found in the reader stream.

    If pat is found in the input stream, content before that occurrence is returned and the delimiter is consumed. If include_delimiter is true, pat itself is included at the end of the result. The returned data may be empty in this case if include_delimiter is false.

    EOF is implicitly treated as a delimiter by reader.read_until(). If pat is not found in the input stream when EOF is reached, trailing data before EOF will be returned (or None if there is no trailing data). In this case, the returned data contains no trailing delimiter even if include_delimiter=true. This can be used to detect the presence of trailing delimiter in the input stream.

    reader.read_until() is cancellation safe as long as the underlying reader implementation is cancellation safe. When reader.read_until() is cancelled, no data will be lost.

    MessageKind

    pub(all) enum MessageKind {
    Binary
    Text
    } derive(
    Debug
    )

    WebSocket message