ilusm.dev

wsc

WebSocket client - create a connection state from a URL, open the socket, send raw data, send a JSON-encoded object, close the connection, register onopen/onmessage/onerror/onclose callbacks, check ready state, and build an auto-reconnect wrapper that retries on disconnect.

Load with: use wsc

What this module does

wsc wraps the embedder's WebSok host object in a clean ilusm record API. You create a connection state with wscne, attach callbacks, then call wscop to open the socket. The auto-reconnect wrapper wsccf/wsclo handles re-dialing up to a configurable retry count with a delay between attempts.

Quick example

use wsc

# Basic connection
w = wscne("wss://api.example.com/ws")
w = wscop(w, \() prn("connected"))
w = wscop(w, \(msg) prn("got: " + msg))
w = wscop(w, \(err) prn("error"))
w = wscop(w, \(code) prn("closed: " + str(code)))
w = wscop(w)  # opens the socket

# Send
wscse(w, "hello")
wscjs(w, {type: "ping", ts: 12345})

# Check ready
prn(wscrd(w))  # tru if open

# Close
wsccl(w)

# Auto-reconnect (3 retries, 1s delay)
cfg = wsccf("wss://api.example.com/ws", {retr: 3, dly: 1000,
    onm: \(msg) handle(msg)})
conn = wsclo(cfg)

Functions

Connection lifecycle

wscne(url)

Creates a connection state record for url. Does not open the socket yet.

wscop(w)

Opens the WebSocket connection. Wires the stored callbacks to the host WebSok object.

wsccl(w)

Closes the connection and sets the internal socket to nil.

wscrd(w)

Returns tru if the socket exists and its ready state is 1 (open).

Sending

wscse(w, data)

Sends raw string data over the WebSocket.

wscjs(w, obj)

JSON-encodes obj and sends it as a string message.

Callbacks

wscop(w, fn) - onopen

Registers the callback called when the connection opens.

wscop(w, fn) - onmessage

Registers the callback called with each incoming message string.

wscop(w, fn) - onerror

Registers the callback called on socket error.

wscop(w, fn) - onclose

Registers the callback called with the close code when disconnected.

Auto-reconnect

wsccf(url, opts)

Creates an auto-reconnect config. Options: retr (retry count, default 3), dly (delay ms, default 1000), ono/onm/one/onc callbacks.

wsclo(cfg)

Opens a connection using the config. On disconnect, automatically retries up to cfg.retr times with cfg.dly ms between attempts.

Notes

  • Requires the host to provide a WebSok object (browser WebSocket or embedder equivalent).
  • Requires trl and jsn.