Multiplayer rooms
This page shows how to make the players of one room talk to each other with SDK.game.room, without running your own server. It covers how a room starts and ends, the limits, the events you receive, what changes in local mode, and a small two-player example you can run. The short reference is in the game module; invite links and the friend tray are in multiplayer and invites; the rules a multiplayer game must meet are in the multiplayer requirements.
What a room is#
A room is a small group of signed-in players who are in the same game and share a room id. The portal keeps the list of members, picks one of them as host, and relays your messages between them. It does not run game logic, check moves or store anything. For physics, matchmaking beyond a lobby, or anti-cheat you still need your own server.
There are three pieces:
| Piece | What it is | Who can write |
|---|---|---|
| Messages | Small JSON values sent with send, to everyone else or to one member. No history, no replay. |
Any member |
| Shared state | A key-value object the whole room can read. A new member receives the current copy first. | The host only |
| Members | The list of players with id, username and profilePictureUrl, plus the host id. |
The platform |
The channel is a game data channel, not a text chat. Do not use it to move free text between players; if you do, the chat rules apply to your game.
Start and end a room#
A room starts when your game calls SDK.game.updateRoom({ roomId, isJoinable, inviteParams }), or when the player joins from an invite and your game then calls updateRoom with the room id it was given. It ends for a player when your game calls SDK.game.leftRoom(), when the player closes the game, or when their connection stays down for more than 30 seconds.
const SDK = window.ZokoGames.SDK;
await SDK.init();
// Host: create a room and make it joinable.
await SDK.game.updateRoom({ roomId: "lobby-7", isJoinable: true, inviteParams: { room: "lobby-7" } });
// Guest: the room id arrives in the invite parameters.
const roomId = SDK.game.getInviteParam("room");
if (roomId) await SDK.game.updateRoom({ roomId });Facts about updateRoom that matter here:
- If you leave out
roomId, the portal makes one up. Room ids are letters, digits,_,.and-, at most 64 characters; other characters are replaced by_. - The first player into a room is its host. Only the host changes
isJoinableandinviteParamsfor the room. - A new room holds as many players as the maximum lobby size you entered at upload, but never more than 100. If the game has no lobby size, the portal uses 8.
- A player who joins a full room, or a room whose host set
isJoinable: false, is refused. Show your own "room full" message; the refusal is not an SDK error code. - The same account in two browser tabs counts as one member.
- An empty room is deleted one minute after its last member left. Its shared state is deleted at once.
From SDK 1.6.0, the host can call updateRoom({ isPublic: true }) to let friends join the room from their friends list; rooms are private by default, and in kids mode they always stay private. Call it after onHostChange reports that this player is the host; a call made before the first onHostChange is ignored.
When rooms are not available#
Rooms need a realtime identity, which only a signed-in player has. In these cases updateRoom still resolves, but nothing is announced and the channel does not work:
| Situation | What your game sees |
|---|---|
| Guest | send and setState reject with roomUnavailable. |
| Kids mode, or a game made for children | The portal never opens realtime for the visitor, so send and setState fail. Do not offer multiplayer there; see kids mode. |
| Signed-in account with no 13+ birthday on file, or an account scheduled for deletion | Same as a guest on the portal side. Calls fail with notInRoom or roomUnavailable. |
| Realtime switched off on the portal | roomUnavailable. |
Offer a sign-in button before you offer a room, with SDK.user.showAuthPrompt(), and let guests play a single-player mode.
In kids mode send and setState always reject with roomUnavailable. SDK.user.isUserAccountAvailable is false there, so use it to hide your multiplayer entry points; see kids mode.
Limits#
| Limit | Value | When it is broken |
|---|---|---|
Message size (send) |
8 KB of JSON | send rejects with payloadTooLarge before anything is sent. |
State patch size (setState) |
8 KB of JSON | setState rejects with payloadTooLarge. |
| Keys in one patch | 64 | invalidArgument. |
| State key | 1 to 40 characters of A-Z a-z 0-9 _ . : - |
invalidArgument. |
| Shared state, total | 64 KB of JSON | stateTooLarge, reported through onError. |
| Message rate | 20 per second per player, burst of 20 | rateLimited; the extra messages are dropped. |
| Players in a room | Your maximum lobby size, at most 100 (8 if none was set) | The join is refused. |
| Room lifetime | While anyone is in it; deleted 1 minute after the last member leaves | Nothing is kept. |
| Reconnect window | 30 seconds | After that the player leaves the room. |
Both send and setState count against the 20 per second. If a player keeps sending more than that, 10 rejected messages inside 10 seconds close their realtime connection; the portal reconnects and rejoins the room, but messages sent meanwhile are lost.
Send less, not faster. Position updates at 10 per second are plenty for most games; send changes, not the whole world.
Events#
Every on* method returns a function that removes the listener. Each also has an add...Listener and remove...Listener form (addMessageListener, removeMessageListener, and so on); both forms do the same.
| Method | Fires when | Arguments |
|---|---|---|
onMessage(cb) |
Another member sent a message. Never for your own. | { from, data, direct, seq, ts }. from, seq and ts are set by the platform. |
onMembers(cb) |
A player joined or left, or a profile changed. | The full list of { id, username, profilePictureUrl }. |
addLeftListener(cb) |
The portal ended your membership without you asking (SDK 1.7.0). | { reason, roomId? }, reason one of left, kicked, closed, disconnected. There is no onLeft; use addLeftListener / removeLeftListener. |
onHostChange(cb) |
The host changed, including the first assignment. | hostId (or null) and isHost (true when it is you). |
onState(cb) |
The shared state changed, or you received it in full after joining. | The whole state, and { keys, rev, by? } describing the change. |
onError(cb) |
The platform refused something after the call had already returned. | { code, message }. |
When addLeftListener fires. It reports a membership that ended on the portal side. left: the server dropped the player from the room without your leftRoom() (the player left from another place, or the portal ended the session, for example a sign-out). kicked: the room goes on but the player is no longer a member. closed: the room service refused the room your updateRoom announced because it is closed. disconnected: the connection to the room service is gone for good (signed out, or the connection was taken over by another one; a short drop that reconnects fires nothing). Before the event, onMembers listeners get an empty list and selfId is null, so a game that only watches members already goes back to its lobby; use the event to tell the player why. It is never sent for a leftRoom() your game made itself (your code already knows, and the call's promise is the answer), and it fires once per room. Call updateRoom again to start or join a room after it. Not sent in kids mode, where there are no rooms.
Reading is synchronous: members(), getState(), isHost() and selfId give the current values. The host's own setState is applied when the platform confirms it, so read the result from onState or getState(), not straight after the await.
seq rises for every message in the room. Gaps are possible; order by it, and do not wait for a missing number.
Host changes#
The first player in is the host. When the host leaves, the member who has been in the room longest becomes host and onHostChange fires for everyone. The shared state stays. Put host duties (starting a round, advancing a counter) behind isHost() and re-check it inside onHostChange, so the game keeps going when the host closes the tab.
Errors#
| Code | Cause | Fix |
|---|---|---|
notInRoom |
updateRoom was not called yet, or the player has no realtime identity. |
Call updateRoom first; check sign-in. |
notHost |
A non-host called setState. |
Guard with isHost(). |
payloadTooLarge |
A message or patch over 8 KB. | Send a smaller value. |
stateTooLarge |
The patch would push the state over 64 KB. | Remove keys with null, or keep bulky data elsewhere. |
unknownMember |
to is not a member of the room, or is yourself. |
Take to from members(). |
rateLimited |
More than 20 messages per second. | Throttle, or merge updates into one message. |
roomUnavailable |
Guest, kids mode or realtime off. | Offer sign-in or a single-player mode. |
invalidArgument |
A value that cannot be turned into JSON, a bad state key or an empty patch. | Fix the call. |
payloadTooLarge, notHost, invalidArgument and roomUnavailable can reject the call itself. rateLimited, unknownMember and stateTooLarge usually arrive later through onError. Catch both. Errors are plain { code, message } objects, not Error instances.
A minimal two-player example#
Each player has a tap counter. Everyone sees every counter, and the host sets the target score. Save it as index.html, serve it from localhost and open it in two tabs; the steps are under test with two tabs.
<!doctype html>
<meta charset="utf-8">
<title>Tap race</title>
<button id="tap">Tap</button>
<button id="copy">Copy invite link</button>
<pre id="out">Starting...</pre>
<script src="https://sdk.zokogames.com/zokogames-sdk-v1.js"></script>
<script>
(async () => {
const SDK = window.ZokoGames.SDK;
await SDK.init();
const room = SDK.game.room;
const out = document.getElementById("out");
const taps = {};
let mine = 0;
const draw = () => {
const target = room.getState().target ?? "?";
const lines = room.members().map((m) => {
const tag = m.id === room.selfId ? " (you)" : "";
return `${m.username}${tag}: ${taps[m.id] ?? 0}`;
});
out.textContent = `Target ${target}${room.isHost() ? " (you are host)" : ""}\n` + lines.join("\n");
};
room.onMembers(draw);
room.onState(draw);
room.onHostChange((hostId, isHost) => {
if (isHost && room.getState().target === undefined) room.setState({ target: 20 }).catch(console.warn);
});
room.onMessage(({ from, data }) => {
if (data.type === "taps") { taps[from] = data.count; draw(); }
});
room.onError((e) => console.warn("room error", e.code, e.message));
const roomId = SDK.game.getInviteParam("room")
?? (SDK.environment === "local" ? "demo" : crypto.randomUUID().slice(0, 8));
await SDK.game.updateRoom({ roomId, isJoinable: true, inviteParams: { room: roomId } });
document.getElementById("tap").onclick = () => {
mine += 1;
taps[room.selfId] = mine;
room.send({ type: "taps", count: mine }).catch(console.warn);
draw();
};
document.getElementById("copy").onclick = async () => {
navigator.clipboard.writeText(await SDK.game.inviteLink({ room: roomId }));
};
window.addEventListener("pagehide", () => SDK.game.leftRoom());
draw();
})();
</script>In this example the host writes target once, every player broadcasts its own counter, and the display redraws on every member, state or message event. It does not handle a late joiner who missed earlier counters; to fix that, send your own counter again from onMembers when the member list grows, or keep each counter in the shared state through the host.
Local mode#
When you open the game from localhost (or add ?useLocalSdk=true), SDK.game.room runs against a stand-in. Tabs of the same origin that call updateRoom with the same roomId are connected through a BroadcastChannel, so two tabs behave like two players. See local testing for how local mode starts.
What is the same as the portal: the 8 KB, 20 per second and 64 KB limits, the error codes, the first-in-is-host rule, host migration, direct messages and the full state a joiner receives.
What differs:
| Difference | Detail |
|---|---|
| Players | The local player is signed in as a mock user (?user_response=logged_out makes it a guest, and then send fails with roomUnavailable). Every tab is its own member, with id <user id>:<tab id>. |
| Room id | If you omit roomId, the page address roomId parameter is used, else local-room. |
| Host | The tab that joined first. A tab that goes silent for about seven seconds is dropped from the member list. |
seq |
Counts what this tab received, not a room-wide number. |
| Lobby size | Not enforced, and isJoinable: false does not refuse anyone. |
| Invites | There are no friends. addJoinRoomListener never fires; pass the room id in the page address. |
| Realtime outages | Not simulated. |
Local mode is not the portal. Before you submit, run the same flow in the Preview tool or the build preview and then with two real accounts.
Test with two tabs#
- Serve the example on
localhostand openhttp://localhost:8080/?sdk_debug=true.sdk_debug=truelogs every SDK call. - Open the same address in a second tab. In local mode both tabs use the room id
demo. - Press Tap in each tab. Both lists should update. The first tab shows "you are host".
- Close the first tab. Within about seven seconds the second tab's list drops the player,
onHostChangefires and the second tab becomes host. - Paste a 9 KB string into a
sendcall from the console and check that it rejects withpayloadTooLarge.
Before you submit#
- The game handles
addLeftListener(back to the lobby, with a message) as well as its own leave button. -
updateRoomis called when the player creates or joins a room, andleftRoomwhen they leave. - The game starts and works for a guest (single player) and tells guests why multiplayer needs sign-in.
- Messages stay under 8 KB and well under 20 per second; the shared state stays small.
- Host duties move correctly when the host leaves; the room does not freeze when anyone drops.
- Both
sendandsetStateerrors are caught, andonErroris handled. - The minimum and maximum lobby size in the submission match what the game allows.
- If players can read each other's text, they can report it with
game.reportChat(SDK 1.4.0). - No free text travels through the room without moderation, and
disableChatis respected for your own chat.
Next steps#
- Multiplayer and invites for join links and the friend tray.
- Multiplayer requirements for what a reviewer checks.
- Kids mode for why rooms are off for children.
- Launch checklist for the full path to a published game.
- Troubleshooting if a call fails.