OxL Reference

data WebSocket

An open WebSocket (RFC 6455), made by WebSocket.connect (client) or handed to the function of Reply.websocket (server). Ping is answered with pong automatically (and also reported by recv). Several tasks may send; only one should recv. close() the socket when done.

Example:

oxl✓ checked in CI
use std.http { Server, ServerConfig, ServerHandle, Router, Request, Reply, Client, Header, HttpConfig, Response, WebSocket, WsConfig, WsKind, WsMessage, SseWriter, SseStream, SseConfig, SseEvent, BodyWriter, Http2, Http2Handle, ResponseStream, chunks }

fn run() -> () | NetError | DecodeError | Panicked  net, io, time {
  let srv = Server.bind(ServerConfig{ port: 0, followNode: false })?
  defer srv.close()
  let stop = srv.handle()
  let base = "http://127.0.0.1:{srv.port()}"
  let router = Router.new().get("/ws", (req: Request) => Reply.websocket((ws: WebSocket) => {
    var open = true
    while open {
      let m = ws.recv()?
      if m.kind == WsKind.Text {
        ws.sendText("echo:{m.text}")?
      } else if m.kind == WsKind.Binary {
        ws.sendBinary(m.payload)?
      } else if m.kind == WsKind.Close {
        open = false
      }
    }
  }))
  scope {
    spawn stop.serve(router)
    let ws = WebSocket.connect("ws://127.0.0.1:{srv.port()}/ws", [], WsConfig{ timeout: 5s })?
    defer ws.close()?
    ws.sendText("hello")?
    print((ws.recv(5s)?).text)
    stop.shutdown()
    ()
  }?
}

fn main() io, net, time {
  match run() {
    NetError _ => print("net error")
    DecodeError _ => print("decode error")
    Panicked _ => print("panicked")
    _ => {}
  }
}
Output
echo:hello
@must_close
pub(api) data WebSocket

Thread safety. several tasks may `send`; only one task should `recv`.

Since. 1.0.0-beta

Fields

pub(api) subprotocol: str

The subprotocol agreed on; empty when none.

pub(api) compressed: bool = false

permessage-deflate (RFC 7692) was negotiated: messages are compressed on the wire, transparently (D-3971).

Methods

connect(url: str, headers: List<Header>, cfg: WsConfig) -> WebSocket | NetError net
Connects to a ws:// or wss:// URL and performs the opening handshake.
sendText(text: str, fragment: i64) -> () | NetError net
Sends a text message.
sendBinary(payload: bytes, fragment: i64) -> () | NetError net
Sends a binary message.
ping(payload: bytes) -> () | NetError net
Sends a ping frame; the peer answers with a pong that recv reports (the answer to an incoming ping is sent automatically).
recv(timeout: Duration?) -> WsMessage | NetError net
Waits for the next message or control frame.
sendClose(code: i64, reason: str) -> () | NetError net
Starts the closing handshake (sends a close frame).
close(code: i64, reason: str, timeout: Duration) -> () | NetError net
Sends a close frame, waits (at most timeout) for the peer's, and releases the connection.

Defined in: std/http/http.oxl:2165

See also