Skip to content

WebSocket API

WebSocket ingress handlers receive a session object that represents a single client connection. The session provides methods for sending messages, managing rooms, and storing per-connection state. In real-time mode (scripts that export tickRate), the onTick callback receives a RealtimeRoomProxy instead.

WebSocketSession

The session parameter is passed to onOpen(session), onMessage(session, message), and onClose(session).

session.id

The unique session ID (read-only).

  • Type: string
javascript
export function onOpen(session) {
  console.log("Client connected:", session.id);
}

session.send(message)

Send a text message to this client.

  • Parameters: message: string
javascript
session.send(JSON.stringify({ type: "welcome", id: session.id }));

session.close()

Close the WebSocket connection.

javascript
if (shouldDisconnect) {
  session.send(JSON.stringify({ type: "kicked", reason: "timeout" }));
  session.close();
}

session.isOpen()

Check if the connection is still open.

  • Returns: boolean

session.getParameter(name)

Get a query parameter from the WebSocket handshake URI.

  • Parameters: name: string
  • Returns: string | null
javascript
// ws://host/ws/chat?room=general&user=alice
const room = session.getParameter("room");   // "general"
const user = session.getParameter("user");   // "alice"

session.getHeader(name)

Get a header from the WebSocket handshake request.

  • Parameters: name: string
  • Returns: string | null
javascript
const token = session.getHeader("Authorization");

session.getRequestPath()

Get the URI path of the WebSocket connection.

  • Returns: string

session.getRemoteAddr()

Get the client's IP address.

  • Returns: string

session.setAttribute(key, value)

Store a custom attribute on this session. Useful for per-connection state like user identity.

  • Parameters: key: string, value: any
javascript
export function onOpen(session) {
  const username = session.getParameter("user");
  session.setAttribute("username", username);
}

session.getAttribute(key)

Retrieve a custom attribute from this session.

  • Parameters: key: string
  • Returns: any
javascript
export function onMessage(session, message) {
  const username = session.getAttribute("username");
  const payload = JSON.stringify({ from: username, text: message });
  session.room("chat").broadcastExcept(payload);
}

session.getAttributes()

Get all custom attributes as a map.

  • Returns: { [key: string]: any }

WebSocketRoom

Rooms provide group communication. Obtain a room handle via session.room(name). The room is not auto-joined — you must explicitly call join().

session.room(roomName)

Get a room proxy for the given room name. Does not join the room — call .join() separately.

  • Parameters: roomName: string
  • Returns: WebSocketRoom

room.join()

Join this room. Rooms are created lazily on first join.

javascript
session.room("lobby").join();

room.leave()

Leave this room. Rooms are automatically deleted when empty.

javascript
session.room("lobby").leave();

room.broadcast(message)

Send a message to all members of this room, including the sender.

  • Parameters: message: string
javascript
session.room("lobby").broadcast(JSON.stringify({
  type: "announcement",
  text: "Server maintenance in 5 minutes"
}));

room.broadcastExcept(message)

Send a message to all room members except the sender.

  • Parameters: message: string
javascript
session.room("lobby").broadcastExcept(JSON.stringify({
  type: "message",
  from: session.getAttribute("username"),
  text: message
}));

room.members()

Get the number of members currently in this room.

  • Returns: number
javascript
const count = session.room("lobby").members();
session.send(JSON.stringify({ type: "roster", online: count }));

room.getName()

Get the room name.

  • Returns: string

WebSocketService (Server-Side)

The WebSocketService is available from any script context via diesel.getWebSocketService(). It provides server-side access to rooms and sessions, enabling push notifications from HTTP handlers, cron jobs, or standalone scripts.

diesel.getWebSocketService()

Returns a WebSocketService proxy.

ws.room(roomName)

Get a server-side room proxy. Always returns a proxy — operations on non-existent rooms are safe no-ops.

  • Parameters: roomName: string
  • Returns: WebSocketServiceRoom
javascript
const ws = diesel.getWebSocketService();
ws.room("stock-updates").broadcast(JSON.stringify({ type: "price", data: stockData }));

ws.listRooms()

Get a list of all active room names.

  • Returns: string[]

ws.roomExists(roomName)

Check if a room exists (has at least one member).

  • Parameters: roomName: string
  • Returns: boolean

ws.getSession(sessionId)

Look up a connected WebSocket session by ID. Returns null if not found.

  • Parameters: sessionId: string
  • Returns: WebSocketSessionInfo | null
javascript
const session = diesel.getWebSocketService().getSession("abc-123");
if (session && session.isOpen()) {
    session.send(JSON.stringify({ type: "hello" }));
}

ws.getActiveSessionIds()

Get the IDs of all connected WebSocket sessions.

  • Returns: string[]

ws.getActiveSessionCount()

Get the number of connected WebSocket sessions.

  • Returns: number

WebSocketServiceRoom (Server-Side)

A server-side room handle returned by diesel.getWebSocketService().room("name"). Unlike the session-scoped WebSocketRoom, this does not include join(), leave(), or broadcastExcept() — those require a sender session.

room.broadcast(message)

Broadcast a message to all members of this room.

  • Parameters: message: string

room.members()

Get the number of members in this room.

  • Returns: number

room.getMemberIds()

Get the session IDs of all members in this room.

  • Returns: string[]

room.getName()

Get the room name.

  • Returns: string

room.exists()

Check if this room exists (has at least one member).

  • Returns: boolean

WebSocketSessionInfo (Server-Side)

A lightweight, read-only session proxy returned by diesel.getWebSocketService().getSession(id). Provides basic info and message sending. Does not include session-scoped operations like room().join(), setAttribute(), getParameter(), or getHeader().

info.id

The unique session ID (read-only).

  • Type: string

info.send(message)

Send a text message to this client.

  • Parameters: message: string

info.isOpen()

Check if the connection is still open.

  • Returns: boolean

info.getRequestPath()

Get the request path (URI) of this WebSocket connection.

  • Returns: string | null

info.getRemoteAddr()

Get the remote IP address of the client.

  • Returns: string | null

Lifecycle Notes

  • Room memberships are automatically cleaned up when onClose returns, even if you don't call leave() manually.
  • The send() method is synchronized on the session — thread-safe for concurrent calls.
  • A single session can join multiple rooms simultaneously.
  • Room operations are backed by an in-memory concurrent map — no database persistence.
  • In real-time mode (scripts that export tickRate), all JS execution runs on a dedicated route thread — no explicit synchronization needed.

RealtimeRoomProxy

The room parameter passed to onTick(room, deltaMs) in real-time WebSocket scripts. Represents all sessions connected to the route. This proxy is only available in real-time mode — per-connection scripts do not have onTick.

INFO

The session argument in onOpen, onMessage, and onClose is still a regular WebSocketSession in both modes. Only onTick receives a RealtimeRoomProxy.

room.broadcast(message)

Send a message to all sessions connected to this route.

  • Parameters: message: string
javascript
export function onTick(room, deltaMs) {
  room.broadcast(JSON.stringify({ type: "tick", time: Date.now() }));
}

room.broadcastExcept(excludeSessionId, message)

Send a message to all sessions except the one with the given ID.

  • Parameters: excludeSessionId: string, message: string

room.send(sessionId, message)

Send a message to a specific session by ID.

  • Parameters: sessionId: string, message: string
  • Returns: booleantrue if the session was found and the message was sent
javascript
export function onTick(room, deltaMs) {
  // Send personalized data to each player
  for (const id of room.getSessionIds()) {
    room.send(id, JSON.stringify({ type: "your-data", id }));
  }
}

room.getSession(sessionId)

Get a session proxy by ID, or null if not connected.

  • Parameters: sessionId: string
  • Returns: WebSocketSession | null

room.getSessionIds()

Get the IDs of all connected sessions on this route.

  • Returns: string[]

room.getSessionCount()

Get the number of connected sessions on this route.

  • Returns: number

room.room(roomName)

Get a server-side room proxy for interacting with the named room system. Same as diesel.getWebSocketService().room(name).

  • Parameters: roomName: string
  • Returns: WebSocketServiceRoom

room.getRoute()

Get the route path this real-time handler is bound to.

  • Returns: string (e.g. /ws/game)

Full Example: Chat Room

javascript
export function onOpen(session) {
  const username = session.getParameter("user") || "anonymous";
  session.setAttribute("username", username);
  session.room("chat").join();

  session.send(JSON.stringify({ type: "welcome", id: session.id }));
  session.room("chat").broadcastExcept(JSON.stringify({
    type: "join",
    user: username
  }));
}

export function onMessage(session, message) {
  const username = session.getAttribute("username");
  session.room("chat").broadcastExcept(JSON.stringify({
    type: "message",
    from: username,
    text: message,
    timestamp: Date.now()
  }));
}

export function onClose(session) {
  const username = session.getAttribute("username");
  session.room("chat").broadcastExcept(JSON.stringify({
    type: "leave",
    user: username
  }));
  // room.leave() is called automatically after onClose returns
}

DieselEngine Scripting Documentation