Search Results

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

  1. Message Format: Use JSON objects for structured data exchange.

  2. State Updates: Use broadcastState() for high-frequency updates (positions) and broadcast() for important events.

  3. Timing: sessionTime is 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.

  4. Error Handling: Always implement onErrorOccurred to handle connection issues.

  5. Topology Choice: Use Star for games needing authoritative host logic, Mesh for cooperative games with direct player interaction.

  6. 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

NameTypeDescription
acceptingJoins readonlyboolTrue while new nodes can join this node's network
appIdstringNames the app or game, so only builds of the same one connect
autoRelayboolWhether the host automatically relays messages between joiners in Star topology
clientTokenstringWhat this node identifies itself with when it joins
clientTokens readonlyvarOn the host, each joiner's clientToken, keyed by its node ID
connected readonlyboolTrue if connected to a network
connectionPhase readonlystringCurrent connection phase when status is Connecting
connectionTimeoutintTimeout in milliseconds for connection attempts. 0 to disable
gracePeriodintHow long, in milliseconds, a node may go unheard before it counts as gone
hostId readonlystringNode ID of the network's host, the same on every node
hostLostReason readonlystringWhy this joiner lost its host, or an empty string
iceServersvarCustom ICE server configuration for NAT traversal
isHost readonlyboolTrue if this node is the network host
latency readonlyintBest RTT across all connected peers in milliseconds. -1 if unknown
linkConditionsvarSimulated network conditions for this node, for testing
maxNodesintMaximum number of nodes allowed in the network
networkId readonlystringCurrent network code
nodeCount readonlyintNumber of nodes currently in the network
nodeId readonlystringThis node's unique identifier
nodes readonlystringList of node IDs currently in the network
passwordstringRoom password a host demands, or the one a joiner gives
peerStats readonlyvarPer-peer transport statistics, always on
phaseTiming readonlyvarTiming breakdown of the connection phases in milliseconds
sessionProperties readonlyvarSession's properties, set by the host with setSessionProperty(), the same on every node
sessionTime readonlyrealSession clock: milliseconds since the host created the network, the same on every node. -1 while not in a network
sessionTimeSynced readonlyboolTrue on the host, and on a joiner once its pings have synced sessionTime to the host's (about 2 seconds after joining)
signalingModeenumerationHow nodes discover and connect to each other
signalingUrlstringCustom signaling server URL for offline/LAN operation
status readonlyenumerationCurrent connection status
syncStats readonlyvarPer-node state-sync statistics, keyed by ORIGIN node id
topologyenumerationNetwork topology to use
verboseboolEnable diagnostic output via diagnosticMessage
verifySignalingCertificateboolWhether a native node checks the signaling server's certificate
wireVersion readonlyintVersion of the message format this build speaks

Methods

MethodReturnsDescription
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

SignalDescription
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)