Network Manager
A WebSocket connection for multiplayer that reconnects by itself, queues messages while offline, measures lag, and supports request and reply messages.
Files: network-manager.js (the component, no dependencies) and network-manager.test.mjs (5 tests).
Copy network-manager.js into your game, for example to src/components/, and import it as an ES module.
Usage
import { createNetwork } from "./network-manager.js";
const net = createNetwork({ url: "wss://my-server.example/game" });
net.on("state", (snapshot) => applySnapshot(snapshot));
net.on("status", (s) => showConnection(s)); // "connecting" | "open" | "reconnecting" | "closed"
net.connect();
net.send("input", { left: true, seq: 12 });
const room = await net.request("join", { room: "ABCD" }); // waits for the server's reply
API
createNetwork({ url, protocols, WebSocket, reconnect: { min, max, factor }, pingEvery, timeout, maxQueue }) → netnet.connect() / net.close()close() stops reconnectingnet.send(type, data) → true if sent now, false if queued (queue keeps the newest maxQueue messages)net.request(type, data, timeoutMs) → Promise of the reply's data; rejects on timeout or an error replynet.on(type, fn) → offmessage types from the server, plus “status”, “open”, “close”, “error”net.status / net.rtt (ms, smoothed) / net.stats → { sent, received, reconnects, queued }
Messages are JSON: { type, data, id? }. A reply has { type: “reply”, id, data } or { type: “reply”, id, error }.
The server should answer { type: “ping”, t } with { type: “pong”, t }.
Engines
| Engine | Notes |
|---|---|
| Vanilla, Phaser, PixiJS, Three.js | yes. Any server that speaks JSON over WebSocket (Node ws, Deno, Cloudflare Durable Objects, Bun). |
| Browsers | all current ones. Bash.tv previews and itch.io pages need wss:// (not ws://). |
Tests
Node tests with a fake WebSocket: connect, queue while offline then flush, reconnect with backoff, no reconnect after close, requests and replies, timeouts, ping and lag, bad messages.
Run them with node --test toolkit/components/network-manager/ (Node 20 or newer, nothing to install).