← Back to Docs
  • index.html
  • Clayground
  • Clayground.Network
  • Network
  • Clayground 2025.2
  • Network QML Type

    Unified P2P networking for games, apps, and distributed systems. More...

    Import Statement: import Clayground.Network

    Properties

    Signals

    Methods

    Detailed Description

    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.

    Signaling Modes

    Network Topologies

    Example Usage

    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) => {
            entities[from].x = data.x
            entities[from].y = data.y
        }
    }
    
    // Host a network
    Button {
        text: "Host"
        onClicked: network.host()
    }
    
    // Join a network
    Button {
        text: "Join"
        onClicked: network.join(codeInput.text)
    }

    See also ClayHttpClient.

    Property Documentation

    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().


    connected : bool [read-only]

    True if connected to a network.


    connectionPhase : string [read-only]

    Current connection phase when status is Connecting.

    Possible values: "signaling", "ice", "datachannel", 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).


    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 [read-only]

    True if this node is the network host.


    latency : int [read-only]

    Best RTT across all connected peers in milliseconds. -1 if unknown.

    Updated every 2 seconds when verbose is true.


    maxNodes : int

    Maximum number of nodes allowed in the network.

    Valid range: 2-8. Default: 8. Must be set before calling host().


    networkId : string [read-only]

    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 (encoded IP) modes.


    nodeCount : int [read-only]

    Number of nodes currently in the network.


    nodeId : string [read-only]

    This node's unique identifier.

    For hosts, this equals networkId. For clients, assigned when connecting.


    nodes : string [read-only]

    List of node IDs currently in the network.


    peerStats : var [read-only]

    Per-peer statistics. Only populated when verbose is true.

    Format: { nodeId: { latency, msgSent, msgRecv, bytesSent, bytesRecv } }


    phaseTiming : var [read-only]

    Timing breakdown of the connection phases in milliseconds.

    After connection: { signaling: 230, ice: 1200, datachannel: 0, total: 1430 }


    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.

    ConstantDescription
    Network.SignalingMode.CloudUses PeerJS server for peer discovery (default). Requires internet. Enables cross-platform Browser <-> Desktop <-> Mobile connectivity.
    Network.SignalingMode.LocalHost runs embedded signaling server. No internet needed. Works on 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"


    status : enumeration [read-only]

    Current connection status.

    ConstantDescription
    Network.Status.DisconnectedNot connected to any network.
    Network.Status.ConnectingConnection in progress.
    Network.Status.ConnectedSuccessfully connected.
    Network.Status.ErrorConnection failed or lost.

    topology : enumeration

    The network topology to use.

    ConstantDescription
    Network.Topology.StarNodes connect only to host (default).
    Network.Topology.MeshAll nodes connect to each other. (Future)

    Must be set before calling host() or join().


    verbose : bool

    Enable diagnostic output and quality monitoring.

    When true, enables:


    Signal Documentation

    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.

    Note: The corresponding handler is onErrorOccurred.


    messageReceived(string fromId, var data)

    Emitted when a reliable message is received.

    Messages sent via broadcast() arrive here.

    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.


    stateReceived(string fromId, var data)

    Emitted when a state update is received.

    Updates sent via broadcastState() arrive here.

    Note: The corresponding handler is onStateReceived.


    Method Documentation

    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)

    Send a state update to all connected nodes.

    Optimized for high-frequency updates like positions.


    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.

    If you're the host, this closes the network for all nodes.


    void sendTo(string nodeId, var data)

    Send a message to a specific node.

    nodeId must be a valid node ID from the nodes list.