Bash.tv → GitHub → itch.io

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

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