RoomMessageEvent

Available since @irtio/client 5.0BrowsersNode

The RoomMessageEvent interface of the Client API is the event a RoomClient fires as its message event, when a message from the room arrives. It extends Event, and has the fields of the web’s MessageEvent that a room’s message uses.

Constructor

new RoomMessageEvent(data, unreliable, from)
data
The event’s data.
unreliable
A boolean, the event’s unreliable.
from
A string or undefined, the event’s from.

The event’s type is "message". The client creates the events it fires.

Instance properties

All are read only. It also has Event’s properties, such as type.

RoomMessageEvent.data
The message: what the room sent as JSON, parsed, or a Uint8Array for a binary message.
RoomMessageEvent.unreliable
Whether the room sent the message unreliably.
RoomMessageEvent.from
undefined in a room with room code.

Description

Two details of RoomMessageEvent have no page of their own.

Relation to MessageEvent

RoomMessageEvent has the web’s data field but isn’t a subclass of MessageEvent, which not every runtime has.

from

from is undefined in a room with room code, whose messages all come from the room. In a native room, where messages come from other players, it’s the sender’s player ID, and "" for a message sent through the server API. Held messages keep it.

Examples

Reading binary and JSON messages

A game whose room sends positions as bytes and everything else as JSON tells them apart by data’s type.

// positions.ts
import { connect, type RoomMessageEvent } from "@irtio/client";

const room = await connect("https://rooms.irt.io/my-game/arena");

function received(event: RoomMessageEvent): void {
  if (event.data instanceof Uint8Array) {
    const view = new DataView(event.data.buffer, event.data.byteOffset, event.data.byteLength);
    console.log(`ball at ${view.getFloat32(0)}, ${view.getFloat32(4)}`);
  } else {
    console.log("event", event.data);
  }
}
room.addEventListener("message", received);

See also

Runtime availability

BrowsersNode
RoomMessageEvent5.05.0