std.net.websocket

WebSocket client for ws:// URLs; wss:// also works on OpenSSL builds (see Overview). Event-driven like TCP/HTTP: install on_message/on_close, then send.

Connect and echo

var ws = std.net.websocket("ws://echo.example/socket")

ws.on_message(fn(data, is_binary) {
  if (is_binary) { print("binary frame:", data) }
  else { print("text:", data) }
})
ws.on_close(fn() { print("socket closed") })

ws.send("hi")                                  # text frame
ws.send({data: "raw bytes", binary: true})     # binary frame

print(ws.is_open())                            # true while connected

std.async.sleep(5000)                          # keep the script alive: exiting would close the connection with it
ws.close()

Reference

Method Description
websocket(url) Constructor — connect to ws:///wss://host:port/path
send(text) Send a text frame
send({data, binary: true}) Send a binary frame
on_message(fn(data, is_binary)) Per incoming frame
on_close(fn()) When the peer closes
on_disconnect(fn(clean)) Whenever the connection is lost; clean is true after a close handshake, false on error drops
last_error() Most recent background error (connection/send failure or callback exception)
is_open() true while the connection is live
close() Close the connection

Frame types

  • Text frames: ws.send("hello") → peer receives text; is_binary == false on arrival.
  • Binary frames: ws.send({data: "bytes", binary: true}) → is_binary == true. Use when sending non-UTF8 payloads or when the server expects binary.

data is always a string (binary payloads are binary strings). Combine with std.crypto/std.hash if you need to encode/decode them.

Lifecycle

  • The constructor connects immediately; is_open() reflects the live state.
  • Like all network objects, callbacks run on background fibers — std.async.sleep keeps the script alive to receive.
  • No reconnection is automatic — on close, create a new websocket(url) if you want to reconnect.
  • To serve websockets instead of connecting, return {websocket: true} from an HTTP Server route — the server handles the handshake, ping/pong, and unmasked-frame enforcement for you.

See also