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 |
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
// Direct token
bearerToken: "your-token-here"
// From environment variable
bearerToken: "env:API_TOKEN"
// From file
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 |
| Mobile (iOS, Android) | - | ClayHttpClient | Partial |
Best Practices
-
Message Format: Use JSON objects for structured data exchange.
-
State Updates: Use
broadcastState()for high-frequency updates (positions) andbroadcast()for important events. -
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 |
|---|---|---|
autoRelay | bool | Whether the host automatically relays messages between joiners in Star topology |
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 |
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 |
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 |
peerStats readonly | var | Per-peer statistics. Only populated when verbose is true |
phaseTiming readonly | var | Timing breakdown of the connection phases in milliseconds |
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 |
topology | enumeration | Network topology to use |
verbose | bool | Enable diagnostic output and quality monitoring |
Methods
| Method | Returns | Description |
|---|---|---|
broadcast(var data) | void | |
broadcastState(var data) | void | |
host() | void | |
join(string networkId) | void | |
leave() | void | |
sendTo(string nodeId, var data) | void |
Signals
| Signal | Description |
|---|---|
connectionTimedOut() | |
diagnosticMessage(string phase, string detail) | |
errorOccurred(string message) | |
messageReceived(string fromId, var data) | |
networkCreated(string networkId) | |
nodeJoined(string nodeId) | |
nodeLeft(string nodeId) | |
stateReceived(string fromId, var data) |