Real-time Magic

Experience the power of Soli's built-in WebSocket support.
Scalable, resilient, and easy to use.

Connecting...
ID: ...
S
System
Welcome to the WebSocket demo! Try sending a message.

1 Define the Route

config/routes.sl
router_websocket("/ws/chat", "websocket#chat_handler");

2 Handle Events with Server-Side Helpers

Instead of returning {"broadcast": ...}, call the ws_* helpers imperatively. Mix sends, broadcasts, and other logic in one handler.

app/controllers/websocket_controller.sl
def chat_handler(event)
  conn_id = event["connection_id"]

  if event["type"] == "connect"
    # Greet just the new connection
    ws_send(conn_id, { "type": "welcome", "id": conn_id })
    # Tell everyone else (hash is auto-JSON-serialized)
    ws_broadcast({ "type": "join", "user": conn_id })
    return {}
  end

  if event["type"] == "message"
    data = event["message"].to_h
    ws_broadcast({
      "type": "message",
      "text": data["text"],
      "from": conn_id
    })
    return {}
  end

  {}
end

Helpers used on this page

  • ws_send(conn_id, msg) — reply to a single connection
  • ws_broadcast(msg) — fan out to every connected client

Other helpers available: ws_broadcast_room, ws_close, ws_list_presence, ws_presence_count, ws_get_presence.

ESC
Type to search...