OxL Reference

method Reply.websocket

Upgrades the connection to a WebSocket and runs body with it; the socket is closed when body returns.

Example:

oxl✓ checked in CI
use std.http { Server, ServerConfig, ServerHandle, Router, Request, Reply, Client, Header, HttpConfig, Response, Middleware, Next, withMiddleware, requireHeader, logRequests, timing, WebSocket, WsConfig, SseWriter, BodyWriter, chunks }

fn body(req: Request) -> str {
  match req.text() {
    str t => t
    DecodeError _ => ""
  }
}

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) => {
    let m = ws.recv()?
    ws.sendText("echo:{m.text}")?
  }))
  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("hi")?
    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:hi
pub(api) static fn websocket(body: fn(WebSocket) -> () | NetError net, io, time escaping, protocols: str = "", compress: bool = true) -> Reply

Since. 1.0.0-beta

Parameters

NameType
bodyfn(WebSocket) -> () | NetError net, io, time escaping, protocols: str = "", compress: bool = true

Returns

Reply

Effects

none declared (pure unless the body says otherwise)

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

See also