WS
Capy
function WS() function WS(request : any)
Bearer invokes WS once for each complete incoming WebSocket message. The handler returns no value. It binds request implicitly as an any, or you can declare request : any explicitly.
Read the message bytes from request.body. request.websocket.connection_id identifies the sender. scope identifies its group, binary distinguishes binary messages, and opcode is 1 for text or 2 for binary. connections lists the current scope's connection IDs.
Use ws_send_to() for a reply to the sender. ws_send() broadcasts to every connection in the selected scope, including the sender. print() does not send a WebSocket frame.
This complete handler echoes a message only to its sender and preserves its text or binary type:
function WS()
{
ws_send_to(string(request.websocket.connection_id), string(request.body), bool(request.websocket.binary))
}
Each message gets a fresh request workspace, so unit variables do not retain connection state. Store per-connection state in request.connection. Bearer carries changes to the next message for that connection. Use a service when state must outlive one connection.
The Boolean result from a send or close call confirms that the runtime accepted a command. It does not confirm delivery or the existence of a target client.
ws_send("echo: " + string(request.body), false)
Output
echo: hello