Connection

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

The Connection interface of the Room API is one open connection from a player’s client to the room. The hooks about one connection, such as onJoin(), onMessage() and onLeave(), receive it, and room.connections holds every open one by its ID.

Room code never constructs a Connection. The room host makes one when a connection opens, and passes the same object to every hook about that connection until it closes.

One connection per player

A player has at most one open connection to a room. When a player connects again, from a new tab or another device, the older connection closes with close code 4012, and onLeave runs for it before onJoin runs for the new one. The older client doesn’t reconnect by itself. The player’s presence entry stays as it was, so other players don’t see a leave and a join.

So a connection stands for a player only while it’s open. Keep what belongs to the player, such as private state, owned entities and bans, by player, not by connection.

Instance properties

Connection.id
The connection’s ID, its key in room.connections. Read only.
Connection.player
The player ID of the player who opened it. Read only.
Connection.meta
The meta claim of the connection’s token, or null. Read only.
Connection.data
An object for the room’s own use, such as the connection’s player entity. It isn’t sent to clients.
Connection.viewTick
The tick of the room state the player was looking at when it sent the input applied this tick. Read only.
Connection.input
The input applied this tick, in the stepper and onTick. Read only.
Connection.rtt
The client’s lowest recent round trip to the room in milliseconds, as the client reports it. Read only.
Connection.protocol
The client protocol the connection speaks. Read only.

Examples

Keeping a player’s ship on the connection

// ships.ts
import { defineRoom, defineSchema, entity, type RoomEntity } from "@irtio/room";

const Ship = entity("ship", { pilot: "string", heading: "f32" }, { key: "pilot" });

export default defineRoom({
  schema: defineSchema({ entities: [Ship] }),
  onJoin(room, connection) {
    connection.data.ship = room.entities.get(Ship, connection.player) ?? room.entities.create(Ship, { pilot: connection.player });
  },
  onMessage(room, connection, message) {
    const ship: RoomEntity<typeof Ship> = connection.data.ship;
    if (typeof message === "number") ship.heading = message;
  },
});

See also

  • Room
  • Presence, for who is in the room rather than which connections are open
  • Room SDK, the whole of @irtio/room on one page

Runtime availability

Hosted roomsirt dev@irtio/testingSelf-hosted room host
Connection0.10.10.10.1