Skip to main content

Multiplayer in Cauldron

A Cauldron deck becomes multiplayer by including a server: a JavaScript module that Castle runs as a real server process, one per session, shared by the players in that session. There's no setting to turn on and no dashboard. Players connect with Multiplayer.join.

The Multiplayer and Turn-based kits already handle the networking and sessions described here, so a deck built on one of them usually writes only its own game rules. Read on to understand how it works, or to write multiplayer code from scratch.

The server entry​

The server is the module named by server.main in the deck's castle.json. Without that setting, it's the first of server/index.js or code/server/index.js (or .ts or .mjs) that exists. To stop a deck being multiplayer, remove the entry and publish from the same copy of the deck that published the server: that push takes the server down. A push from a different copy, such as a fresh download of the deck's files, leaves the published server in place.

Other options under server in castle.json:

  • maxPlayers: players per session. The default is 8, and the most is 24.
  • tickRate: how many times a second onTick runs. The default is 20, the most is 30, and 0 turns ticks off.

The published server can be at most 5 MB.

Server callbacks​

The server module's default export is a set of callbacks. Each one gets the session first:

export default {
onStart(session) {}, // once, before anyone joins
onPlayerJoin(session, player) {}, // player: { playerId, userId, username, isAnonymous }
onPlayerLeave(session, player) {},
onMessage(session, player, data) {}, // data is what the client sent, already parsed
onTick(session) {}, // only when server.tickRate > 0
onReplaced(session) {}, // you published a new version; this session keeps the old one
async onShutdown(session) {}, // the session is ending; awaited before it stops
};

Use the session to talk to players and keep data:

  • send(playerId, data) sends to one player, and broadcast(data, { except }) sends to everyone, optionally leaving some out.
  • disconnect(playerId, reason) removes a player.
  • players lists who's connected. sessionId, deckId and mode describe the session.

TypeScript servers can import these types from castle-web-sdk/server.

Joining from the deck​

import { Multiplayer } from "castle-web-sdk";

const conn = await Multiplayer.join({ mode: "named", key: "lobby-1" });
conn.onMessage((data) => { /* from your server */ });
conn.onRoster(({ players, you }) => { /* who is here */ });
conn.send({ move: "left" });

The mode decides who the player ends up with:

  • public puts the player in a shared session for the deck. If they opened the deck from a Castle party, they join the party's session instead.
  • party joins the Castle party the player is already in.
  • named puts everyone who passes the same key in one session. Use it for room codes and invite links.

Playing alone​

Sometimes a player can't be connected to a server: the deck is private, it hasn't been published with a server, or no server is free. Then Multiplayer.join still succeeds, but returns a single-player connection with conn.isSolo set, so make sure the deck is playable alone. conn.soloReason says why:

  • private_deck: make the deck Unlisted or Public.
  • no_server_bundle: publish the deck with a server entry.
  • unavailable: anything else, such as a player who isn't signed in.

Only you, the deck's creator, see private_deck and no_server_bundle. Other players see unavailable for those too.

Multiplayer.join can still fail outright, for example for a party join when the player isn't in a party, so catch its errors too.

Rules for a fair game​

  • The server is in charge. Deck code runs on the player's device and can be modified, so check every move on the server and send the result back for clients to draw.
  • Trust identity from Castle, not from messages. Castle verifies the player passed to your callbacks. Use player.userId, and never trust a name or id a client puts inside data.
  • Know which id you need. userId identifies an account and never changes. playerId identifies one connection: it stays the same if the player reconnects within about a minute, and changes after that. One account can be in a session twice, from two tabs.

What the server can and can't do​

A session server has about 128 MB of memory, no file system that lasts, and no network access: no fetch, no database, no outside APIs. Keep state in memory and send it to clients.

A session ends a minute after its last player leaves, after 15 minutes with no activity, or after 24 hours at most. Its memory goes with it.

Saving data​

A session's memory doesn't outlast it, so anything that should come back later has to be saved.

  • The kits save for you. The Multiplayer kits keep where objects and players are, and the Turn-based kit keeps each room's table, from their own servers.
  • Each player's own data can be saved from the deck itself with Store: Store.me for data other players can read, and Store.private for data only that player sees.
  • Shared data belongs to the server. Once a deck publishes a server, the deck-wide Store.deck scope is the server's: players can still read it, but a write from the deck fails, including the Store.deck examples in the Store reference. That way a modified client can't fake shared progress or results. Leaderboards work the same way: on a deck with a published server, a Store.board(name).submit from the deck is refused with CAULDRON_STORAGE_FORBIDDEN, while reading a board with top and get still works. To save from a server you write yourself, see Saving data from the server.

Save as things change, not only at the end. onShutdown runs only when a session stops cleanly, and a crash skips it.

Limits​

  • Client to server: at most 16 KB per message. Sending a bigger one throws an error. A client can send about 30 messages a second, with short bursts allowed; messages beyond that are dropped, and a client that keeps going over is disconnected. Throttle input rather than sending on every animation frame.
  • Server to client: at most 64 KB per message. A session can send about 40 + 40 × players messages a second, and about 1 MB a second in total. broadcast(data) counts once however many players receive it, while send and broadcast(data, { except }) count once per recipient. Messages over the budget are dropped, and a server that floods far past it for a long time is shut down.

Both size limits include a small envelope Castle adds to each message, so leave a little room.

The practical pattern is to broadcast one snapshot of every player's state per tick, rather than a separate message per player.

Messages are JSON by default. To send raw bytes, pass a typed array, DataView or ArrayBuffer; the receiver gets a Uint8Array.

Testing and publishing​

  • Testing: open the deck's Play panel in two tabs or on two devices. Both join the same session. Editing the server restarts it, and clients reconnect.
  • Publishing: every new session runs the new version. A session already running keeps the code it started with for now: its server gets onReplaced, and each player's connection closes with replaced. A player who joins again with public gets the new version, while a named or party join goes back to the same session. About ten minutes after you publish, Castle ends any session still on the old code, telling players the game was updated; its onShutdown still runs, and the next join gets the new version. The multiplayer kits rejoin for you.
  • Visibility: a Private deck always runs solo, for you too. Make it Unlisted to test with other people.
  • Player counts: once a deck has a published server, its card in the Castle app and on castle.xyz shows how many people are playing it right now. Inside the deck, Rooms.list lists its public sessions and how many players are in each.

Next: A/B tests · Back to How decks run