Skip to content

Room API (Server-side)

Considering that you already set up your server, now it's time to register session handlers, and start accepting connections from your users.

You'll define session handlers creating classes that extends from Room.

import { Room, Client } from "colyseus";

export class MyRoom extends Room {
    // Authorize client based on provided options before WebSocket handshake is complete
    onAuth (options: any) { }

    // When room is initialized
    onInit (options: any) { }

    // Checks if a new client is allowed to join. (default: `return true`)
    requestJoin (options: any, isNew: boolean) { }

    // When client successfully join the room
    onJoin (client: Client) { }

    // When a client leaves the room
    onLeave (client: Client, consented: boolean) { }

    // When a client sends a message
    onMessage (client: Client, message: any) { }

    // Cleanup callback, called after there are no more clients in the room. (see `autoDispose`)
    onDispose () { }
}

Abstract methods

Room handlers can implement all these methods.

onInit (options)

Is called once when room is initialized. You may specify custom initialization options when registering the room handler.

Tip

The options will contain the merged values you specified on Server#register() + the options provided by the first client on client.join()

requestJoin (options, isNew)

Parameters:

  • options: The options provided by the client (client.join()), merged with options provided by the server (gameServer.register()).
  • isNew: will be true for rooms being created and false for existing ones.

Synchronous function to check if a new client is allowed to join.

If left non-implemented, this method returns true, allowing any client to connect.

onAuth (options)

Can be used to verify authenticity of the client that's joining the room.

If left non-implemented it returns true, allowing any client to connect.

See authentication section.

onJoin (client, options, auth?)

Parameters:

Is called when client successfully join the room, after requestJoin and onAuth has been succeeded.

onMessage (client, data)

Is called when a client sends a message to the server. Here's where you'll process client actions to update the room's state.

Example:

onMessage (client, data) {
    let player = this.playersByClientId.get(client);

    if (data.command === "left") {
        player.x -= 1;

    } else if (data.command === "right") {
        player.x += 1;
    }
}

onLeave (client, consented)

Is called when a client leave the room. If the disconnection was initiated by the client, the consented parameter will be true, otherwise, it will be false.

You can define this function as async. See graceful shutdown

onDispose ()

Cleanup callback, called after there are no more clients in the room.

You can define this function as async. See graceful shutdown

Public properties

clients: WebSocket[]

The array of connected clients. See Web-Socket Client.

maxClients: number

Maximum number of clients allowed to connect into the room. When room reaches this limit, it is locked automatically. Unless the room was explicitly locked by you via lock() method, the room will be unlocked as soon as a client disconnects from it.

patchRate: number

Frequency to send the room state to connected clients (in milliseconds)

See state synchronization.

autoDispose: boolean

Automatically dispose the room when last client disconnect. (default: true)

locked: boolean (read-only)

This property will change on these situations:

  • The maximum number of allowed clients has been reached (maxClients)
  • You manually locked, or unlocked the room using lock() or unlock().

clock: ClockTimer

A ClockTimer instance, used for timing events.

Public methods

Room handlers have these methods available.

setState (object)

Set the new room state.

Warning

Do not call this method for updates in the room state. The binary patch algorithm is re-set every time you call it.

Tip

You'll usually call this method only once (on Room.onInit()) in your room handler.

setSimulationInterval (callback[, milliseconds=16.6])

(Optional) Create the simulation interval that will change the state of the game. Default simulation interval: 16.6ms (60fps)

setPatchRate (milliseconds)

Set frequency the patched state should be sent to all clients. (default: 50 = 20fps)

setMetadata (metadata)

Set metadata for the room instance. This metadata is public when requesting the room list through client.getAvailableRooms() method.

setSeatReservationTime (seconds)

(Default=3) Set the number of seconds a room can wait for a client to effectively join the room. You should consider how long your onAuth() will have to wait for setting a different seat reservation time. The default value is usually good enough.

send (client, message)

Send a message to a particular client.

this.send(client, { message: "Hello world!" });

broadcast ( message )

Send a message to all connected clients.

lock ()

Locking the room will remove it from the pool of available rooms for new clients to connect to.

unlock ()

Unlocking the room returns it to the pool of available rooms for new clients to connect to.

disconnect ()

Disconnect all clients, then dispose.

allowReconnection (client, seconds)

Allow the specified client to rejoin into the room. Must be unsed inside onLeave() method.

async onLeave (client) {
  // flag client as inactive for other users
  this.state.inactivateClient(client);

  try {
    // allow disconnected client to rejoin into this room until 20 seconds
    await this.allowReconnection(client, 20);

    // client returned! let's re-activate it.
    this.state.activateClient(client);

  } catch (e) {

    // 20 seconds expired. let's remove the client.
    this.state.removeClient(client);
  }
}