Lobby Room

Colyseus provides a built-in LobbyRoom that can be used to list all available rooms in your game server.

Features:

  • Automatically lists all rooms created with enableRealtimeListing().
  • Automatically updates the list of rooms when a room is created, joined, left or disposed.
  • Allows filtering rooms by name and metadata.

The source-code for LobbyRoom is fairly straightforward. You can check it out here. You are encouraged to extend it and create your own lobby room if you need more control over the behavior.

Server

Expose the lobby room

server.ts
import { LobbyRoom } from "colyseus";
// ...
gameServer.define("lobby", LobbyRoom);

Enable realtime listing on your game room

When realtime listing is enabled, the LobbyRoom is notified automatically during onCreate(), onJoin(), onLeave() and onDispose().

server.ts
gameServer
  .define("my_room", MyRoom)
  .enableRealtimeListing();

Updating the lobby

If you have updated the metadata of your room (via .setMetadata()), you will need to call updateLobby() to trigger an update for the lobby.

MyRoom.ts
import { Room, updateLobby } from "colyseus";
 
class MyRoom extends Room {
 
  onCreate() {
 
    //
    // This is just a demonstration
    // on how to call `updateLobby` from your Room
    //
    this.clock.setTimeout(() => {
 
      this.setMetadata({
        gameMode: "deathmatch",
      }).then(() => updateLobby(this));
 
    }, 5000);
 
  }
 
}

Client

The LobbyRoom will send messages to the client whenever a room is added, removed or updated.

client.ts
import { Client, RoomAvailable } from "colyseus.js";
 
const client = new Client("ws://localhost:2567");
const lobby = await client.joinOrCreate("lobby");
 
let allRooms: RoomAvailable[] = [];
 
lobby.onMessage("rooms", (rooms) => {
  allRooms = rooms;
});
 
lobby.onMessage("+", ([roomId, room]) => {
  const roomIndex = allRooms.findIndex((room) => room.roomId === roomId);
  if (roomIndex !== -1) {
    allRooms[roomIndex] = room;
 
  } else {
    allRooms.push(room);
  }
});
 
lobby.onMessage("-", (roomId) => {
  allRooms = allRooms.filter((room) => room.roomId !== roomId);
});

Filtering rooms

Filtering rooms by name or metadata can be done by providing the filter option when joining the lobby:

client.ts
const lobby = await client.joinOrCreate("lobby", {
  filter: {
    name: "my_room",
    metadata: {
      gameMode: "deathmatch",
    }
  }
});

Alternatively, you can also dynamically change the filter by sending a "filter" message to the lobby room:

lobby.send("filter", {
  name: "my_room",
  metadata: {
    gameMode: "deathmatch",
  }
});