Network Plugin
The Clay Network plugin provides networking capabilities for Clayground applications, including P2P multiplayer for games and HTTP client functionality for web API integration.
Getting Started
import Clayground.Network
Core Components
P2P Multiplayer
- ClayMultiplayer (WASM) - WebRTC-based P2P multiplayer using PeerJS for signaling. No dedicated server required.
- ClayNetworkUser (Desktop) - TCP/UDP-based local network P2P with automatic peer discovery.
HTTP Client
- ClayHttpClient - Configurable HTTP client that generates API methods from endpoint definitions.
- ClayWebAccess - Low-level HTTP request handler supporting GET and POST with authentication.
ClayMultiplayer (WebAssembly)
Browser-based P2P multiplayer using WebRTC Data Channels. One player hosts, others join via a simple room code.
Quick Start
import Clayground.Network
ClayMultiplayer {
id: network
maxPlayers: 4
topology: ClayMultiplayer.Star
onRoomCreated: (code) => {
// Share this code with friends
console.log("Room code:", code)
}
onPlayerJoined: (playerId) => {
console.log("Player joined:", playerId)
}
onMessageReceived: (from, data) => {
// Handle chat, game events, etc.
if (data.type === "chat")
chatLog.append(data.text)
}
onStateReceived: (from, data) => {
// Handle position updates, etc.
entities[from].x = data.x
entities[from].y = data.y
}
}
// Host a game
Button {
text: "Host Game"
onClicked: network.createRoom()
}
// Join a game
Button {
text: "Join"
onClicked: network.joinRoom(roomCodeInput.text)
}
Network Topologies
| Topology | Description | Best For |
|---|---|---|
| Star | All players connect to host only. Host relays messages. | Competitive games, authoritative server logic |
| Mesh | All players connect to each other directly. | Cooperative games, lower latency |
ClayMultiplayer {
topology: ClayMultiplayer.Star // or ClayMultiplayer.Mesh
}
Message Types
| Method | Signal | Delivery | Use Case |
|---|---|---|---|
broadcast(data) |
messageReceived |
Reliable, ordered | Chat, game events, important state |
broadcastState(data) |
stateReceived |
Optimized for frequency | Entity positions, real-time stats |
broadcastState(data, key) |
stateReceived (with key) |
As above, sequenced per key, sent batched | One update per object |
sendTo(playerId, data) |
messageReceived |
Reliable, ordered | Direct player messages |
Multiplayer Game Example
Item {
property var players: ({})
ClayMultiplayer {
id: network
maxPlayers: 8
onPlayerJoined: (playerId) => {
players[playerId] = createPlayer(playerId)
}
onPlayerLeft: (playerId) => {
if (players[playerId]) {
players[playerId].destroy()
delete players[playerId]
}
}
onStateReceived: (from, data) => {
if (players[from]) {
players[from].x = data.x
players[from].y = data.y
}
}
}
// Broadcast local player position
Timer {
interval: 50
repeat: true
running: network.connected
onTriggered: {
network.broadcastState({
x: localPlayer.x,
y: localPlayer.y
})
}
}
}
ClayNetworkUser (Desktop/Native)
Local network P2P using TCP/UDP with automatic peer discovery. Available on non-WASM platforms.
ClayNetworkUser {
id: player
name: "Player1"
Component.onCompleted: joinGroup("game-room-1")
onNewMessage: (from, message) => {
console.log(nameForId(from) + " says: " + message)
}
onNewParticipant: (userId) => {
sendDirectMessage(userId, "Welcome!")
}
}
ClayHttpClient
Declarative HTTP API client with auto-generated methods.
ClayHttpClient {
id: api
baseUrl: "https://api.example.com"
endpoints: {
"getUser": "GET users/{userId}",
"createPost": "POST posts {postData}",
"updateUser": "POST users/{userId} {userData}"
}
bearerToken: "your-api-token"
onReply: (requestId, code, response) => {
const data = JSON.parse(response)
console.log("Success:", data)
}
onError: (requestId, code, error) => {
console.error("API Error:", error)
}
Component.onCompleted: {
api.getUser(123)
api.createPost({ title: "Hello", content: "World" })
}
}
Authentication Options
Three schemes, each configured by its own properties:
// Bearer token -> "Authorization: Bearer <token>"
bearerToken: "your-token-here"
// HTTP basic -> "Authorization: Basic <base64(user:password)>"
basicAuthUser: "alice"
basicAuthPassword: "s3cret"
// API key -> a header of its own, "X-API-Key" unless renamed
apiKey: "abc123"
apiKeyHeader: "X-API-Key"
bearerToken takes precedence over basicAuthUser/basicAuthPassword — a
request carries one Authorization header. apiKey is independent and can
accompany either.
Every credential value can be given literally or read from somewhere else:
// Direct value
bearerToken: "your-token-here"
// From environment variable
bearerToken: "env.API_TOKEN"
// From file (contents are trimmed)
bearerToken: "file:///path/to/token.txt"
Platform Support
| Platform | P2P Multiplayer | HTTP Client | Status |
|---|---|---|---|
| WebAssembly (Browser) | ClayMultiplayer (WebRTC) | ClayHttpClient | Supported |
| Desktop (Linux, macOS, Windows) | ClayNetworkUser (TCP/UDP) | ClayHttpClient | Supported |
| Android | - | ClayHttpClient | Partial |
| iOS | - | - | Not in iOS builds yet (#476) |
Best Practices
-
Message Format: Use JSON objects for structured data exchange.
-
State Updates: Use
broadcastState()for high-frequency updates (positions) andbroadcast()for important events. -
Timing:
sessionTimeis a clock all nodes share; every message and state carries the session time it was sent at (sentAt), so “this happens at t” means the same moment on every node. -
Error Handling: Always implement
onErrorOccurredto handle connection issues. -
Topology Choice: Use Star for games needing authoritative host logic, Mesh for cooperative games with direct player interaction.
-
Room Codes: Room codes are 6 alphanumeric characters, case-insensitive.
Technical Details
WASM Implementation
- Signaling: PeerJS public cloud server (free, no setup required)
- Transport: WebRTC Data Channels
- Reliability: Supports both reliable (TCP-like) and unreliable (UDP-like) modes
Native Implementation
- Discovery: UDP broadcast on local network
- Transport: TCP for reliable messaging
- Groups: Logical grouping for targeted messaging
API Reference
ClayHttpClient Configurable HTTP client with automatic API method generation
Network Unified P2P networking for games, apps, and distributed systems
Properties
| Name | Type | Description |
|---|---|---|
acceptingJoins readonly | bool | True while new nodes can join this node's network |
appId | string | Names the app or game, so only builds of the same one connect |
autoRelay | bool | Whether the host automatically relays messages between joiners in Star topology |
clientToken | string | What this node identifies itself with when it joins |
clientTokens readonly | var | On the host, each joiner's clientToken, keyed by its node ID |
connected readonly | bool | True if connected to a network |
connectionPhase readonly | string | Current connection phase when status is Connecting |
connectionTimeout | int | Timeout in milliseconds for connection attempts. 0 to disable |
gracePeriod | int | How long, in milliseconds, a node may go unheard before it counts as gone |
hostId readonly | string | Node ID of the network's host, the same on every node |
hostLostReason readonly | string | Why this joiner lost its host, or an empty string |
iceServers | var | Custom ICE server configuration for NAT traversal |
isHost readonly | bool | True if this node is the network host |
latency readonly | int | Best RTT across all connected peers in milliseconds. -1 if unknown |
linkConditions | var | Simulated network conditions for this node, for testing |
maxNodes | int | Maximum number of nodes allowed in the network |
networkId readonly | string | Current network code |
nodeCount readonly | int | Number of nodes currently in the network |
nodeId readonly | string | This node's unique identifier |
nodes readonly | string | List of node IDs currently in the network |
password | string | Room password a host demands, or the one a joiner gives |
peerStats readonly | var | Per-peer transport statistics, always on |
phaseTiming readonly | var | Timing breakdown of the connection phases in milliseconds |
sessionProperties readonly | var | Session's properties, set by the host with setSessionProperty(), the same on every node |
sessionTime readonly | real | Session clock: milliseconds since the host created the network, the same on every node. -1 while not in a network |
sessionTimeSynced readonly | 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 |
signalingUrl | string | Custom signaling server URL for offline/LAN operation |
status readonly | enumeration | Current connection status |
syncStats readonly | var | Per-node state-sync statistics, keyed by ORIGIN node id |
topology | enumeration | Network topology to use |
verbose | bool | Enable diagnostic output via diagnosticMessage |
verifySignalingCertificate | bool | Whether a native node checks the signaling server's certificate |
wireVersion readonly | int | Version of the message format this build speaks |
Methods
| Method | Returns | Description |
|---|---|---|
broadcast(var data) | void | |
broadcastState(var data, string key) | void | |
despawn(string id) | bool | |
flushState() | void | |
host() | void | |
join(string networkId) | void | |
leave() | void | |
objectInfo(string id) | var | |
objectOwner(string id) | string | |
objects(string type) | list | |
sendObjectState(string id, var data) | void | |
sendTo(string nodeId, var data) | void | |
setOwner(string id, string nodeId) | bool | |
setSessionProperty(string name, var value) | bool | |
settleObjectState(string id, var data) | void | |
spawn(string type, var props, var options) | string | |
stateAgeMs(string nodeId, string key) | int | |
transitMs(string nodeId) | real |
Signals
| Signal | Description |
|---|---|
connectionTimedOut() | |
diagnosticMessage(string phase, string detail) | |
errorOccurred(string message) | |
hostLost(string reason, string message) | |
joinRefused(string reason, string message) | |
messageReceived(string fromId, var data, real sentAt) | |
networkCreated(string networkId) | |
nodeJoined(string nodeId) | |
nodeLeft(string nodeId) | |
objectDespawned(string id, string type) | |
objectOwnerChanged(string id, string owner) | |
objectSpawned(string id, string type, string owner, var props) | |
objectStateReceived(string id, var data, real sentAt) | |
sessionPropertyChanged(string name, var value) | |
signalingLost() | |
stateReceived(string fromId, var data, real sentAt, string key) |