WebSocket API reference
Build a Vectrune WebSocket broadcast endpoint with connection hooks, message handlers, and a browser client.
Save as websocket.rune
WebSocket endpoints are mounted by the REST app. This example declares /chat and broadcasts incoming messages to connected clients on that path. Stop other port 3000 examples before starting it.
#!RUNE
@App
name = Chat server
type = REST
port = 3000
@Websocket/chat
on_connect:
log "Client connected"
on_message:
ws.broadcast /chat body
on_disconnect:
log "Client disconnected"
vectrune websocket.runeConnect from a browser
Open the developer console on a local HTTP page. This client connects, sends a plain text message when ready, and logs broadcasts. Open a second client to observe fan-out. An HTTPS page may block an insecure ws:// connection.
const socket = new WebSocket('ws://127.0.0.1:3000/chat');
socket.onmessage = event => console.log(event.data);
socket.onopen = () => socket.send('Hello from the browser');
// When finished:
// socket.close();Handlers and builtins
- on_connect runs after registration of the connection.
- on_message handles generic incoming text; body contains the message.
- on_disconnect runs when the receive loop ends.
- ws.id returns the current connection identifier.
- ws.send takes a path, connection identifier, and message.
- ws.broadcast takes a path and message, and sends to clients registered on that path.
Structured messages
JSON messages with a type property can dispatch to @Event sections. Start with the plain text broadcast example before adding event-specific handlers. Connection and memory registries live in the current process; multiple server processes do not share them automatically.