0xDocs 0x.limo

Docs / JavaScript SDK

@0xlimo/net

socket.io and Colyseus adapters that send a game server's broadcasts through the 0x broadcast service, which fans them out to players through trees of players over WebRTC.

A broadcast leaves your game server once per group, however many players are in it. The 0x broadcast service signs it and fans it out to the group's players, in order. Most players get it from other players through WebRTC trees, checked against the service's signature. Your game's emit/on calls do not change:

  • Broadcasts (io.emit, io.to(group).emit, socket.broadcast.emit, socket.to(group).emit, Colyseus room.broadcast) go through the service.
  • Everything else stays on socket.io or Colyseus as before: unicast (socket.emit, client.send), rooms that are not groups, binary payloads, everything players send, and Colyseus state sync.
  • A player who cannot reach the service gets the broadcasts over socket.io or Colyseus instead, so nobody misses one.

Registry version: 0.1.2 (depends on ws). Typings ship with the package. The generated API reference lists every type and function.

bash
npm install @0xlimo/net --@0xlimo:registry=https://0x.limo/npm/

Sites built by the CLI also get the browser files as ./x1/net/ (with ./x1/net/wasm/, the service's own player client), so the page needs no bundler.

#socket.io

js
import { Server } from "socket.io";
import WebSocket from "ws";
import { connectServiceServer, routeSocketIoBroadcasts } from "@0xlimo/net";

const io = new Server(http, { cors: { origin: true } });
// On 0x hosting the URL and token come from the environment (ZEROX_BCAST_*): no arguments needed.
const service = await connectServiceServer({ WebSocket });
routeSocketIoBroadcasts(io, {
  service,
  playerUrl: process.env.ZEROX_BCAST_PLAYER_URL,
  groups: (room) => room.startsWith("match:"),     // rooms that are interest groups
});
service.on("close", () => process.exit(1));        // the host restarts you with a fresh connection

setInterval(() => io.emit("state", snapshot()), 50);   // leaves once, reaches everyone

How it works:

  1. On connection, routeSocketIoBroadcasts registers the player with the service and sends x1:join {player, ticket, url} to that socket.
  2. x1SocketIo connects to the service with it. It uses the WebSocket player endpoint by default (direct only), or connect when you give one.
  3. Broadcasts arrive on channel CHANNEL_SOCKETIO (0x5310) as JSON {ev, args}, and are handed to the socket's own listeners.

The service puts a player in one group at a time. Every player starts in the namespace's group. Joining a room that groups accepts moves the player there, and leaving it moves them back. Without groups, the namespace is the only group.

#Colyseus

js
import { connectServiceServer, routeColyseusBroadcasts } from "@0xlimo/net";

class GameRoom extends Room {
  async onCreate() {
    const service = await connectServiceServer();
    routeColyseusBroadcasts(this, { service, playerUrl: process.env.ZEROX_BCAST_PLAYER_URL });
  }
}

The room is the group. types (a list or a predicate) limits which message types go through the service. The channel is CHANNEL_COLYSEUS (0xc015).

#Player trees and privacy

connectMeshPlayer({url, player, ticket, wasm, mesh: true, rtcConfig}) runs the service's own player client (wasm). With mesh: true, the page joins the player trees over WebRTC data channels. Without it, every broadcast comes from the service directly. stats() gives {direct, fanout, framesFromPeers, badFrames, links}.

The player's sharing choice in the launcher reaches the page as a URL parameter:

  • ?p2p=relay (Private): connectMeshPlayer forces iceTransportPolicy: "relay", so every WebRTC link goes through the 0x TURN relay.
  • ?p2p=0 (Off): no peer-to-peer.

#Hosted servers: the environment

0x deploy-server runs your server with these variables (see @0xlimo/host):

VariableValue
ZEROX_BCAST_URL, ZEROX_BCAST_SERVER_URLthe service's game-server endpoint (a loopback forwarder inside the sandbox)
ZEROX_BCAST_PLAYER_URLthe player endpoint, handed to clients (wss://play.0x.limo/x1/bcast/player)
ZEROX_BCAST_TOKENyour app's own service token

The host also sets each of these under its old name, X1_* (for example X1_BCAST_TOKEN), so servers written before the rename to 0x keep working; read ZEROX_* first and fall back to X1_*.

connectServiceServer() with no url uses hostedService(). That reads ZEROX_BCAST_TOKEN, plus ZEROX_BCAST_URL, ZEROX_BCAST_PLAYER_URL and ZEROX_BCAST_INSTANCE when set. Without them it uses HOSTED_BCAST (wss://play.0x.limo/x1/bcast/server and …/player). With neither a url nor a token, it throws connectServiceServer: no url, and no ZEROX_BCAST_TOKEN for the hosted service.

#Local development and tests

  • 0x dev runs a development broadcast service at /x1/bcast/server and /x1/bcast/player. It is startDevService from @0xlimo/net/dev-service: the real wire and rules, direct only, no signing.
  • createMemoryService() is the service in one process, with the real rules. It suits tests and single-process games: server() returns a ServiceServer, and player({player, ticket}) returns a ServicePlayer.
  • groupId(name) maps a room name to the service's u32 group id (FNV-1a).
  • newPlayer() makes a fresh {player, ticket}.

#The lower-level service API

If you do not use socket.io or Colyseus, drive the service yourself:

js
import { connectServiceServer, newPlayer, groupId } from "@0xlimo/net";

const service = await connectServiceServer();
const { player, ticket } = newPlayer();
service.register(player, groupId("lobby"), ticket);   // hand {player, ticket, url} to the client yourself
service.broadcast(groupId("lobby"), 1, new TextEncoder().encode("hi"));
service.on("from", (p, channel, bytes) => { /* a player's message */ });

On the player side, connectServicePlayer({url, player, ticket}) returns a ServicePlayer with on("data", (channel, bytes) => {}), send(channel, bytes) and close().