RoomClient: message event

Available since @irtio/client 5.0BrowsersNode

The message event of the RoomClient interface fires when a message from the room arrives, one the room sent with room.send() or room.broadcast().

Syntax

addEventListener("message", (event) => {})

Event type

A RoomMessageEvent. It extends Event and adds these properties:

data Read only
The message: what the room sent as JSON, parsed, or a Uint8Array for a binary message.
unreliable Read only
true when the room sent it unreliably.
from Read only
undefined in a room with room code, whose messages all come from the room. In a native room, the sender’s player ID, or "" for a message sent through the server API.

Description

Messages before a listener

A room’s messages can reach the client before connect() resolves, such as those it sends in onJoin(). The client holds reliable messages that arrive before the first message listener is added, up to 100, and gives them to the listeners once the code that added the first one has run, so listeners added together all get them. So await connect(...) then room.addEventListener("message", ...) gets every message the room sent on join.

Unreliable messages aren’t held: before the first listener, they’re dropped. After the first message listener has been added, nothing is held, so a listener added later gets only messages from then on.

Order

Messages keep the order the room sent them in, held ones first. A held message is delivered after the state updates that arrived with it are applied. Unreliable messages can arrive out of order with reliable ones, and some never arrive.

Examples

Showing chat from the room

The room relays chat as JSON objects. The client checks each message’s type before using it, since one room can send several kinds of message.

// chat-log.ts
import { connect } from "@irtio/client";

const room = await connect("https://rooms.irt.io/my-game/tavern");
const log = document.querySelector("#chat")!;

room.addEventListener("message", (event) => {
  if (event.data instanceof Uint8Array) return;
  // The room's messages aren't typed, so check the shape before using it
  const message = event.data as { type?: string; from?: string; text?: string };
  if (message.type !== "chat") return;
  const line = document.createElement("p");
  line.textContent = `${message.from}: ${message.text}`;
  log.append(line);
});

See also

Runtime availability

BrowsersNode
message event5.05.0