Unified P2P networking for games, apps, and distributed systems. More...
| Import Statement: | import Clayground.Network |
Network provides peer-to-peer connectivity using WebRTC Data Channels. One node hosts a network, others join using a simple network code. No dedicated server infrastructure required.
Works across platforms: Browser (WASM), Desktop, and Mobile can all connect to each other when using Internet signaling mode.
import Clayground.Network
Network {
id: network
maxNodes: 4
topology: Network.Topology.Star
signalingMode: Network.SignalingMode.Cloud
onNetworkCreated: (code) => {
console.log("Share this code:", code)
}
onNodeJoined: (nodeId) => {
console.log("Node joined:", nodeId)
}
onMessageReceived: (from, data) => {
if (data.type === "chat")
chatLog.append(data.text)
}
onStateReceived: (from, data, sentAt) => {
entities[from].sync.push(data, sentAt) // a StateInterpolator
}
}
// Host a network
Button {
text: "Host"
onClicked: network.host()
}
// Join a network
Button {
text: "Join"
onClicked: network.join(codeInput.text)
}
See also ClayHttpClient.
acceptingJoins : bool |
True while new nodes can join this node's network.
True on a host whose signaling connection is up. While the Cloud signaling connection is lost (signalingLost()) it is false - the network goes on, but nobody new can find the host - and it turns true again once the host is back on the server. Always false on a joiner.
appId : string |
Names the app or game, so only builds of the same one connect.
Default: empty. A joiner whose appId differs from the host's is refused with "incompatible-app". Set it to the same string in every build of a game when other Clayground apps could be handed its code. Must be set before calling host() or join().
autoRelay : bool |
Whether the host automatically relays messages between joiners in Star topology.
Default: true. When enabled, messages sent by one joiner are automatically forwarded to all other joiners through the host.
Set to false if the host wants full control over message relay (e.g., for server-authoritative validation, anti-cheat, or custom game logic). When false, the host must manually forward messages using broadcast().
clientToken : string |
What this node identifies itself with when it joins.
A random token unless set. A joiner sends it in its handshake, and the host keeps it in clientTokens next to the joiner's node ID - a node ID changes with every join, the token need not. Store it and set it again on the next start so a host can recognise a joiner that comes back. Must be set before calling join().
clientTokens : var |
On the host, each joiner's clientToken, keyed by its node ID.
A joiner is in it from the moment it is in nodes until it leaves. Empty on a joiner: a token is between a joiner and its host.
connected : bool |
True if connected to a network.
connectionPhase : string |
Current connection phase when status is Connecting.
Possible values: "signaling", "ice", "handshake" (a joiner waiting for the host to take it), or "" when not connecting.
connectionTimeout : int |
Timeout in milliseconds for connection attempts. 0 to disable.
When a connection attempt exceeds this duration, connectionTimedOut() is emitted and the connection is terminated. Default: 15000 (15 seconds).
gracePeriod : int |
How long, in milliseconds, a node may go unheard before it counts as gone.
Every node pings its peers every 2 seconds, and a peer it has heard nothing from for half a second right away; every peer answers. A peer that leaves a ping unanswered for this long, sending nothing at all - not even a pong - has crashed or lost its link: it is reported in nodeLeft(). On a joiner that peer is the host, and the network ends as when the host leaves (see leave()). A crashed peer is noticed within the grace period plus about a second.
A link that drops out for less than this and comes back loses no node. Default: 5000. 0 turns the check off; a node then leaves only by saying so or when its connection fails.
hostId : string |
The node ID of the network's host, the same on every node.
On the host it equals nodeId; on a joiner it is the host's entry in nodes, and messages and states the host sends itself arrive with it as their sender. It names the host in both signaling modes and on every platform, so a game decides "is this the host's word?" by comparing against it instead of guessing the host's ID format. Empty string while not in a network; a joiner knows it from the moment it starts connecting to the host.
hostLostReason : string |
Why this joiner lost its host, or an empty string.
Set before connected turns false, so a handler on connected or status can read it; host() and join() clear it again.
| Constant | Description |
|---|---|
"host-left" | The host called leave(). |
"host-timeout" | The host left its pings unanswered for gracePeriod: it crashed, froze or its link went dark. |
"connection-lost" | The connection to the host closed or failed without a goodbye. |
Empty when this node left by itself or never lost a host. More codes may follow; treat an unknown one like "connection-lost".
See also hostLost().
iceServers : var |
Custom ICE server configuration for NAT traversal.
Override the default STUN servers. Accepts a list of URL strings and/or objects with credentials for TURN servers.
Default: uses Google's public STUN servers.
Example with TURN server:
iceServers: [
"stun:stun.l.google.com:19302",
{ urls: "turn:relay.example.com", username: "user", credential: "pass" }
]
isHost : bool |
True if this node is the network host.
latency : int |
Best RTT across all connected peers in milliseconds. -1 if unknown.
Updated every 2 seconds while connected.
linkConditions : var |
Simulated network conditions for this node, for testing.
Default: empty, which changes nothing. Set it to make this node sit behind a bad link, on one machine, without touching the operating system: everything the node sends and everything it receives over its data channels is conditioned, each direction on its own.
loss (0..1) - share of state updates (broadcastState()) that are lost. Reliable messages are never lost; a lost one would be retransmitted, so they arrive late instead.latencyMs - added to every packet, each way.jitterMs - a random 0..jitterMs added on top. State updates may overtake each other this way, reliable messages stay in order.bandwidthKbps - packets leave one after another at this rate (kbit/s, 0 = no cap); a full link delays everything behind.blackout - while true, state updates are lost and reliable messages are held; when it ends, they arrive in order.dropSignaling - while true, the signaling server cannot be reached: host() and join() end in errorOccurred(), and a live Cloud signaling connection is cut as if the server had dropped it (what follows is that of a real drop, see signalingLost()). A Local host is its own signaling server and hosts regardless.Takes effect immediately, also while connected; assign a whole new object to change it. Packets already under way keep their schedule.
network.linkConditions = { loss: 0.1, latencyMs: 80, jitterMs: 20 }
network.linkConditions = { blackout: true } // the link goes dark
network.linkConditions = {} // a clean link again
Works the same on desktop, mobile and in the browser.
maxNodes : int |
Maximum number of nodes allowed in the network.
Valid range: 2-8. Default: 8. Must be set before calling host().
networkId : string |
The current network code.
Empty string if not connected. For hosts, this is the code to share. Works identically for cloud (e.g., "ABC123") and local (e.g., "L1HGF041-6Y4-K7QP2MXA": encoded IP, port and join secret) modes.
nodeCount : int |
Number of nodes currently in the network.
nodeId : string |
This node's unique identifier.
For hosts, this equals networkId. For clients, assigned when connecting.
nodes : string |
List of node IDs currently in the network.
password : string |
The room password a host demands, or the one a joiner gives.
Default: empty. A host with a password refuses every joiner that does not give the same one: the joiner gets joinRefused() with "wrong-password" and errorOccurred("Wrong password"), and never appears in nodes. A host without a password takes any joiner.
The joiner sends it in its handshake over the data channel, which is encrypted, so it never passes the signaling server: knowing the network code is no longer enough to get in. Works the same for Cloud and Local signaling, on desktop, mobile and in the browser. Must be set before calling host() or join().
peerStats : var |
Per-peer transport statistics, always on.
Format: { nodeId: { latency, msgSent, msgRecv, bytesSent, bytesRecv, stateSent, stateRecv, stateChannel, stateBacklog, stateOrdered, stateMaxRetransmits } }. stateChannel is "unreliable" once the lossy state channel is negotiated and "fallback" while state still travels over the reliable channel. stateOrdered and stateMaxRetransmits are what the channel state travels on reports of itself: false and 0 for the state channel, true and -1 (no limit) for the reliable one. Both backends count the same fields; the property changes with the pongs, every 2 s.
phaseTiming : var |
Timing breakdown of the connection phases in milliseconds.
After connection: { signaling: 230, ice: 1200, datachannel: 0, handshake: 15, total: 1445 }
sessionProperties : var |
The session's properties, set by the host with setSessionProperty(), the same on every node.
A map of name to value - a seed, the level being played, or an object or array of them: any value JSON can carry arrives whole on every node. A node that joins late gets them with its welcome. It already holds the new value when sessionPropertyChanged() fires. Empty outside a network.
sessionTime : real |
The session clock: milliseconds since the host created the network, the same on every node. -1 while not in a network.
It is the host's monotonic clock, so no NTP adjustment of a wall clock moves it. The host reads it directly; a joiner syncs to it with the pings it sends the host anyway, a burst of them right after joining and one every 2 seconds after that, and lands within a few milliseconds of it - also over a link with 100 ms of latency and jitter. Until sessionTimeSynced is true it may step; after that it only runs, never back.
Every message and state carries the session time it was sent at (sentAt in messageReceived and stateReceived), so a node can tell how long ago something happened on another node, or agree with all of them on a moment to come ("this lands at t").
Read it when you need it: it changes every millisecond, but a binding to it is only re-evaluated when the clock is set, synced or reset.
sessionTimeSynced : bool |
True on the host, and on a joiner once its pings have synced sessionTime to the host's (about 2 seconds after joining).
signalingMode : enumeration |
How nodes discover and connect to each other.
Signaling is only used for initial peer discovery. Once connected, all data flows directly peer-to-peer via WebRTC data channels.
| Constant | Description |
|---|---|
Network.SignalingMode.Cloud | Uses a PeerJS server for peer discovery (default): the public one, or a self-hosted relay via signalingUrl. Enables cross-platform Browser <-> Desktop <-> Mobile connectivity. |
Network.SignalingMode.Local | Host runs an embedded signaling server; the network code carries its IP, port and a join secret. No internet needed, local network only. Not available on WASM (browser). |
signalingUrl : string |
Custom signaling server URL for offline/LAN operation.
When set, overrides the default PeerJS cloud signaling server. Use this to point at a local PeerJS-compatible relay (e.g. clay-dev-server).
Example: "wss://myhost:8090/peerjs"
A wss server must present a certificate this machine trusts for its host name, or connecting ends in errorOccurred(); see verifySignalingCertificate.
status : enumeration |
Current connection status.
| Constant | Description |
|---|---|
Network.Status.Disconnected | Not connected to any network. |
Network.Status.Connecting | Connection in progress. |
Network.Status.Connected | Successfully connected. |
Network.Status.Error | Connection failed or lost. |
syncStats : var |
Per-node state-sync statistics, keyed by ORIGIN node id.
Unlike peerStats this also covers nodes whose state arrives relayed through the host. Format: { nodeId: { seq, recv, dropped, ageMs } } - dropped counts stale updates discarded by sequence checks, ageMs is the time since the newest accepted state.
A node that sent keyed states (broadcastState() with a key) also has keys, { key: { seq, recv, dropped, ageMs } } per key, batches, the datagrams they came in, and maxBatchBytes, the largest of them; its recv and dropped include the keyed states.
topology : enumeration |
verbose : bool |
Enable diagnostic output via diagnosticMessage.
Statistics (latency, peerStats, syncStats) are always maintained; verbose additionally enables connection phase reporting and ICE candidate details through the diagnosticMessage signal.
verifySignalingCertificate : bool |
Whether a native node checks the signaling server's certificate.
Default: true. A wss signaling server whose certificate does not verify - self-signed, expired, or issued for another host name - ends the connection attempt in errorOccurred() and status Error.
Set to false only for a server you control whose certificate cannot verify, such as clay-dev-server's self-signed one. Without the check, anyone on the path to the server can swap the session descriptions, and with them the keys the data channels are encrypted with.
Applies to desktop and mobile. The browser checks the certificate itself and ignores this property. On Windows the certificate is not checked yet, whatever this says (a libdatachannel limitation). Must be set before calling host() or join().
wireVersion : int |
The version of the message format this build speaks.
Two builds with different wire versions cannot play together: a joiner is refused with "incompatible-version", and so is one that meets a host from before the handshake. Clayground raises it when what goes over the data channels changes.
connectionTimedOut() |
Emitted when a connection attempt exceeds connectionTimeout.
Note: The corresponding handler is onConnectionTimedOut.
diagnosticMessage(string phase, string detail) |
Emitted with diagnostic info when verbose is true.
Provides visibility into connection phases, ICE candidates, and state transitions.
Note: The corresponding handler is onDiagnosticMessage.
errorOccurred(string message) |
Emitted when a connection error occurs.
Also emitted on a joiner whose network ended because the host left, crashed or lost its connection; status is Disconnected then, and hostLost() came first with the reason for a game to act on. Never match the text of message - it is for people.
Note: The corresponding handler is onErrorOccurred.
hostLost(string reason, string message) |
Emitted on a joiner whose network ended with its host.
reason is one of hostLostReason's codes, already in that property when connected turned false; message says it in words. It comes after connected is false and every node was reported in nodeLeft(), and errorOccurred(message) follows.
Note: The corresponding handler is onHostLost.
joinRefused(string reason, string message) |
Emitted on a joiner the host did not take.
Joining starts with a handshake: the joiner's wire version, appId, password and clientToken go to the host, which takes the joiner or refuses it. reason says why, for the game to act on:
| Constant | Description |
|---|---|
"incompatible-version" | The two builds speak different wire versions (wireVersion), or one of them predates the handshake. |
"incompatible-app" | The host's appId is another one. |
"wrong-password" | The password is not the host's. |
"handshake-failed" | The host's answer made no sense. |
"refused" | The host refused without a reason, e.g. a full network. |
message says it in words; errorOccurred(message) follows, and status is Error. The node is not in a network any more, so it can join again - with the right password, for one.
Note: The corresponding handler is onJoinRefused.
messageReceived(string fromId, var data, real sentAt) |
Emitted when a reliable message is received.
Messages sent via broadcast() and sendTo() arrive here. sentAt is the sessionTime the sender sent it at, or -1 when the sender did not include one; sessionTime - sentAt is how long it took. Handlers that only take (fromId, data) keep working.
Note: The corresponding handler is onMessageReceived.
networkCreated(string networkId) |
Emitted when a network is successfully created.
The networkId is a short code that other nodes can use to join.
Note: The corresponding handler is onNetworkCreated.
nodeJoined(string nodeId) |
Emitted when a node joins the network.
Note: The corresponding handler is onNodeJoined.
nodeLeft(string nodeId) |
Emitted when a node leaves the network.
Note: The corresponding handler is onNodeLeft.
objectDespawned(string id, string type) |
A replicated object is gone: despawned, its owner left, or the network ended.
Note: The corresponding handler is onObjectDespawned.
objectOwnerChanged(string id, string owner) |
The object id belongs to owner now.
Note: The corresponding handler is onObjectOwnerChanged.
objectSpawned(string id, string type, string owner, var props) |
A replicated object came to life on this node.
Emitted on every node for every spawn() - on the spawner at once, elsewhere when the host passes it on - and on a node that joins late for each object already there. props are the ones given to spawn(); the object's state comes with objectStateReceived.
Note: The corresponding handler is onObjectSpawned.
See also Replicas.
objectStateReceived(string id, var data, real sentAt) |
The owner of object id sent its state.
Only its owner's state arrives here; a state from any other node, or one that arrives after the object's despawn, is dropped. sentAt is the sessionTime the owner sent it at. A ReplicatedObject applies it on its own.
Note: The corresponding handler is onObjectStateReceived.
sessionPropertyChanged(string name, var value) |
The host set the session property name to value.
It fires on every node, the host included, and on a late joiner once per property with its welcome. sessionProperties already holds value when it fires.
Note: The corresponding handler is onSessionPropertyChanged.
signalingLost() |
Emitted when the Cloud signaling connection drops after it was up.
Nodes already connected keep their data channels; status, connected and nodes stay as they are and messages keep flowing. The node reconnects to the server under the same ID, retrying every few seconds - the server may hold on to the old connection for a while. Meanwhile a host takes no new joiners: acceptingJoins is false until it is back. A joiner still connecting gets no further help from the server and may run into connectionTimeout.
While connected, a node keeps the connection alive with the PeerJS heartbeat, so this means the server or the network dropped it. The same on desktop, mobile and in the browser.
Note: The corresponding handler is onSignalingLost.
stateReceived(string fromId, var data, real sentAt, string key) |
Emitted when a state update is received.
Updates sent via broadcastState() arrive here. sentAt is the sessionTime when the sender called broadcastState(), or -1 when the sender did not include one; hand it to StateInterpolator::push so the snapshot lands on the sender's timeline instead of its arrival time. key is the key the update was sent with, or an empty string for one sent without. Handlers that only take (fromId, data) or (fromId, data, sentAt) keep working.
Note: The corresponding handler is onStateReceived.
void broadcast(var data) |
Send a reliable message to all connected nodes.
Messages are delivered reliably and in order. data should be a JavaScript object.
void broadcastState(var data, string key) |
Send a state update to all connected nodes.
Optimized for high-frequency updates like positions: travels over an unordered channel without retransmissions (lost packets are simply skipped) and carries a sequence number so receivers drop stale updates instead of applying them late. Use broadcast for anything that must arrive (events like attacks, level changes, chat).
Without key the update goes out at once, and the sequence is the sender's: an update is stale behind any newer one from that node. Send one snapshot of everything this way.
With key - one per object, say - an update is stale only behind a newer one from that node for the same key, so a late update for one object is never dropped for another's. Keyed updates leave together when control returns to the event loop (once per frame for updates sent from one frame's handlers) or at flushState(), packed into datagrams of about 1200 bytes at most; a second update for a key before then replaces the first. They arrive in stateReceived with their key. Keys are strings; numbers are converted.
bool despawn(string id) |
Remove object id on every node. False when this node may not: only its owner and the host despawn an object.
On the host it takes effect at once; on a joiner when the host passes it on.
void flushState() |
Send the keyed state updates queued so far now.
broadcastState() with a key queues the update until control returns to the event loop; call this to send the queue earlier, e.g. right after the updates of one tick.
void host() |
Create a new network and become the host.
On success, emits networkCreated() with a code that can be shared. Does nothing if already connected.
void join(string networkId) |
Join an existing network using its code.
The networkId should be the code provided by the host. Does nothing if networkId is empty or already connected.
void leave() |
Leave the current network.
Says goodbye to every peer first, so they report this node in nodeLeft() at once instead of after the grace period. If you're the host, this closes the network for all nodes: each joiner's status turns Disconnected, its hostLostReason is "host-left", and it gets hostLost() and errorOccurred().
var objectInfo(string id) |
Object id as {id, type, owner, props, onOwnerLeft, state}, or an empty object for none. state is its newest state, missing while there is none.
string objectOwner(string id) |
The owner of object id, or an empty string for no object.
list objects(string type) |
Every live object, as objectInfo() gives it; with type, only those of that type.
void sendObjectState(string id, var data) |
Send the state of object id, which this node owns.
Lossy and batched, like broadcastState() with a key. A ReplicatedObject does this for you; settleObjectState() sends a state that must arrive.
void sendTo(string nodeId, var data) |
Send a message to a specific node.
nodeId must be a valid node ID from the nodes list.
bool setOwner(string id, string nodeId) |
Hand object id to nodeId. False when this node may not: only its owner and the host hand an object over.
On the host it takes effect at once; on a joiner when the host passes it on - objectOwnerChanged() tells.
bool setSessionProperty(string name, var value) |
Host only: set a session property for every node, and for every node that joins later. False on a joiner.
value is anything JSON can carry: a number, a string, a bool, or an object or array of them, nested. Every node, the host included, holds it as JSON carries it.
See also sessionProperties.
void settleObjectState(string id, var data) |
Send the state of object id reliably, newer than every state sent before - for the last one of an object that came to rest, which a lost update must not leave stale.
string spawn(string type, var props, var options) |
Create a replicated object; returns its id, or an empty string when it could not be spawned.
The object exists on every node, and on every node that joins later, until it is despawned. type and props say what it is, for the game to make something of in objectSpawned (or a Replicas); the network gives it an id of its own, "<node id>:<n>", never used again. A game that keeps its own key - a player's clientToken, an enemy's spawn index - puts it in props.
options:
owner - the node that owns it, this one by default. Only the host spawns for another node.onOwnerLeft - "despawn" (default): the object goes when its owner leaves; "host": it passes to the host.Only the owner's state for an object counts. The spawner has the object at once; on the other nodes it arrives through the host. A spawn the host does not take comes back to the spawner as objectDespawned(). Needs the Star topology.
int stateAgeMs(string nodeId, string key) |
Milliseconds since the newest accepted state from nodeId, or -1 if none was received yet.
With key, the newest accepted state nodeId sent with that key.
real transitMs(string nodeId) |
How long the fastest state from nodeId of the last 3 seconds took to arrive, in milliseconds of sessionTime, or NaN before one arrived.
It is the offset between nodeId's timeline and arrival here, estimated once per sender: a StateInterpolator given this network and nodeId places its snapshots with it instead of estimating the offset on its own. A state relayed by the host counts both hops.