Skip to main content

Multiplayer

Multiplayer.join connects the deck to its Cauldron server. Pick a public session, the current Castle party, or a stable named room:

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

const connection = await Multiplayer.join({ mode: "public" });
connection.onRoster(({ players, you }) => {
console.log(`${you?.username} is one of ${players.length} players`);
});
connection.onMessage((message) => receiveServerMessage(message));
connection.send({ type: "ready" });

Attach onMessage in the same step that receives the connection (right after await Multiplayer.join(...)). A listener attached later gets only what arrives after it.

Named rooms use { mode: "named", key: "room-name" }; party sessions use { mode: "party" }. Only one connection can be live per deck instance. The SDK reconnects temporary socket drops automatically. onStateChange reports acquiring, connecting, connected, reconnecting, and closed; its optional metadata distinguishes a server bye, a replaced server version, an explicit leave, and connection failures. The reconnect retry budget counts 30 seconds of foreground time; time while the page is hidden or frozen does not spend it, and a stall of the page's JavaScript (a debugger pause, an app pausing its web view) spends at most two seconds. After any return the SDK tries the reconnect credential at least once before giving up on it. Retries wait for the page to become visible and resume. A drop found as the page comes back from being hidden, frozen or suspended is retried at once; one met while the page is running waits a short backoff first. A server rejecting the credential or confirming the session ended can still trigger a fresh join sooner.

connection.reconnect() starts recovery for a connected socket and returns true; otherwise it returns false, including in solo mode.

connection.serverBundleId and connection.serverBundleSha256 identify the server publication running the connected session. These read-only diagnostics are null before a live connection, while disconnected, in solo mode, or when the host does not provide them. The ID identifies a publication; the SHA-256 identifies its code bytes, so two publications can share a hash. Read the values again after a reconnect. They describe the running server, not the client bundle or the deck’s newest save.

Experimental: Multiplayer.join({ mode: "public", pongTimeoutMs: 10_000 }) reconnects if a keepalive ping receives no pong within the given milliseconds. Omitting the option (or passing 0) preserves the existing keepalive behavior. The deadline starts at a ping, normally sent every 25 seconds; it is not a deadline for game messages. A deadline callback delayed by more than one second (for example during page suspension) sends one fresh ping and waits a full deadline before reconnecting. Only one such extension is allowed without a pong, so repeated timer throttling cannot postpone recovery indefinitely.

During local development, reloading a Play panel restores that panel's session when its dev server is still running. A separate Play panel joins separately.

When Castle selects solo fallback, the returned connection has isSolo === true, a one-player roster, and no server process. Calls to send are accepted but do nothing. soloReason says why: private_deck or no_server_bundle are the creator's to fix (change the deck's visibility, or publish a deck that has a server entry); anything else reports unavailable. Client→server frames are limited to 16 KB on the wire.

Limits​

A client may send about 30 messages per second; going past that closes the socket, so throttle pose or input sends rather than sending one per animation frame.

A session may send about 40 + 40 × connected players frames per second, with roughly two seconds of burst and about 1 MiB/s of bytes. session.send costs one frame per call, session.broadcast(data) costs one frame however many players are connected, and session.broadcast(data, { except }) is a loop of sends, so it costs one frame per recipient. Frames over the budget are dropped silently and never retried — the session keeps running — so broadcast one snapshot per tick instead of sending a tailored message per player. Each client reads every entry in that snapshot, its own included: the server's copy of its hp, score and match state is authoritative, and only its own position stays locally predicted.

Binary messages​

Pass any typed array, DataView, or ArrayBuffer to client send, server send, or server broadcast to send its raw bytes. Receivers always get those bytes as a Uint8Array; reconstruct another view type such as Float32Array on receipt. Multi-byte values use the sender platform's byte order. Every other payload uses JSON. Client→server messages are capped at 16 KB and server→client messages at 64 KB, for both JSON and binary frames. Both caps are on the frame, and a binary frame includes a one-byte protocol tag, so the largest payload is one byte under the cap. A published server bundle on an older runtime throws TypeError: This Castle runtime does not support binary multiplayer messages yet.

Server callbacks are the default export from the deck's server entry. They are session-first and receive only platform-trusted player identities:

export default {
onPlayerJoin(session, player) {
session.broadcast({ type: "joined", playerId: player.playerId });
},
onMessage(session, player, message) {
session.broadcast({ from: player.playerId, message });
},
};

TypeScript server entries can import callback, session, player, and platform handle types from castle-web-sdk/server. Server transport has no runtime dependency on a WebSocket package.

session.sessionId, session.deckId and session.mode say which session this is.

session.experiment​

A deck with experiments reads a player's variants on the server too. Castle resolves them and delivers them with the join, so they are the same arms the player's page reads and nothing a client can claim.

  • session.experiment(player, name) is the variant a connected player (the player object or its playerId) has in name, or null when they are in no such experiment.
  • session.experiments(player) is all of them, { name: variant }.

The first session.experiment of each name for a player's join records an exposure, as the client's first read does; session.experiments records none.

Both answer from onPlayerJoin until the player leaves, and null / {} after. The variants are never on the player object, so a roster or state built from session.players does not show one player's arm to another; send a variant to other clients only when the game means to.

export default {
onPlayerJoin(session, player) {
const lives = session.experiment(player, "starting_lives") === "five" ? 5 : 3;
state.players[player.playerId] = { lives };
},
};