Application types
WebSockets in REST apps
WebSockets are a feature of REST applications. Use @Websocket to mount a persistent connection and respond to connection and message events.
#!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"
Reading the syntax
- Keep @App type = REST. @Websocket/chat mounts the WebSocket endpoint at /chat.
- on_connect:, on_message:, and on_disconnect: contain the steps for each event. The received message is available as body.
- ws.broadcast /chat body sends the message to every connected client on /chat. Use ws.send when targeting a single connection.
Run locally
Save this source as websocket.rune and connect a WebSocket client to ws://127.0.0.1:3000/chat. Open two clients to try broadcasting.
vectrune websocket.runeThis example needs the native server. WebSocket is not a standalone @App type, and the browser sandbox does not run native socket hooks.