@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, Colyseusroom.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.
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
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 everyoneimport { connectMeshPlayer, loadBroadcastWasm, x1SocketIo } from "./x1/net/index.js";
const wasm = await loadBroadcastWasm(new URL("./x1/net/wasm/", location.href).href);
const ice = await fetch("./p2p/ice").then((r) => r.json()).catch(() => ({}));
const socket = x1SocketIo(io(location.origin, { path: "/x1/game/my-arena/socket.io" }), {
connect: (j) => connectMeshPlayer({ ...j, wasm, mesh: true, rtcConfig: { iceServers: ice.iceServers } }),
});
socket.on("state", render); // unchanged socket.io handlersHow it works:
- On connection,
routeSocketIoBroadcastsregisters the player with the service and sendsx1:join {player, ticket, url}to that socket. x1SocketIoconnects to the service with it. It uses the WebSocket player endpoint by default (direct only), orconnectwhen you give one.- 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
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 });
}
}import { x1Colyseus } from "@0xlimo/net";
const room = x1Colyseus(await client.joinOrCreate("game")); // wrap before onMessage handlers
room.onMessage("tick", onTick);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):connectMeshPlayerforcesiceTransportPolicy: "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):
| Variable | Value |
|---|---|
ZEROX_BCAST_URL, ZEROX_BCAST_SERVER_URL | the service's game-server endpoint (a loopback forwarder inside the sandbox) |
ZEROX_BCAST_PLAYER_URL | the player endpoint, handed to clients (wss://play.0x.limo/x1/bcast/player) |
ZEROX_BCAST_TOKEN | your 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 devruns a development broadcast service at/x1/bcast/serverand/x1/bcast/player. It isstartDevServicefrom@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 aServiceServer, andplayer({player, ticket})returns aServicePlayer.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:
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().
