RoomDefinition: onMessage() hook

Available since @irtio/room 0.1Hosted roomsirt dev@irtio/testingSelf-hosted room host

The onMessage() hook of a room definition runs for each message a connection sends.

Syntax

defineRoom({
  onMessage(room, connection, message, info) {},
});

Parameters

room
The Room.
connection
The Connection that sent the message.
message
The message, typed unknown: a Uint8Array for a binary message, else the decoded JSON. It comes from the client, so check it before trusting it.
info

An object with this property:

unreliable
true when the client sent the message unreliably.

Return value

None, or a Promise, which the room doesn’t wait for.

Exceptions

If onMessage throws, or its promise rejects, the error is logged with the room, player and tick, and the message is dropped. The room keeps running.

Description

A message is handled as it arrives, between ticks. In a room with ticks, what onMessage changes goes out with the next tick’s state update; in a room without ticks, once the code yields.

The connection’s owner writes that came before the message are applied first, through writes, so onMessage sees what the player wrote. A reliable message always comes after the writes the client made before it; an unreliable one can overtake them.

A client may send at most 120 messages a second; past that the router closes it with close code 4005. For a request that needs a reply, use a call instead; see calls.

Examples

A chat line

// chat.ts
import { defineRoom } from "@irtio/room";

export default defineRoom({
  onMessage(room, connection, message) {
    const m = message as { type?: string; text?: unknown };
    if (m.type !== "chat" || typeof m.text !== "string") return;
    room.broadcast({ type: "chat", from: connection.player, text: m.text.slice(0, 200) });
  },
});

See also

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
onMessage()0.10.10.10.1