# Game Hub v1 – multiplayer server spec
A generic real-time multiplayer server for browser games (three.js, Babylon, Phaser, plain canvas …).
It handles **rooms, players, player state, events and shared room state**. It does **not** know your
game rules: your game code decides what positions, shots, damage and walls mean. That makes it a good fit
for a Fortnite-like game built by one person, where the game logic lives in the client.
> **For Claude Code:** this document is the complete contract. Implement against it exactly.
> The fastest path is to import the ready-made client module (section 3) instead of writing the raw
> WebSocket protocol yourself. Never hard-code the key in the source code or commit it (section 2).
---
## 1. Endpoints
| What | URL |
|---|---|
| WebSocket | `wss://hub.4p.dk/ws` |
| Client module (ES module) | `https://hub.4p.dk/client.js` |
| This spec (Markdown) | `https://hub.4p.dk/spec.md` |
| Deploy your game to its own address | `https://hub.4p.dk/deploy.md` |
| Test page (open in two tabs) | `https://hub.4p.dk/test.html` |
| Health | `GET https://hub.4p.dk/health` → `{"ok":true,...}` |
| Your project's live rooms | `GET /stats` with header `x-hub-key: <KEY>` |
CORS is open, so a game served from `localhost`, GitHub Pages, Netlify etc. can connect.
## 2. The key
You get a short secret key from the server owner, like `K7QX-M2PA`. It identifies **your project**:
only clients with the same key can see each other. Case, spaces and dashes don't matter.
- The player (you) types the key into the game once, for example on the start screen or in a settings panel.
Save it in `localStorage` so it's remembered. **Do not put it in the source code or in git.**
- For local development you can also read it from a `?key=` URL parameter or a `.env` file that is in `.gitignore`.
- A wrong key → `error` with code `bad_key`. 10 wrong keys from one IP within a minute → blocked for 5 minutes.
## 3. Quick start with the client module (recommended)
```js
import { connectHub } from 'https://hub.4p.dk/client.js';
const key = localStorage.getItem('hubKey') || prompt('Server key?');
localStorage.setItem('hubKey', key);
const hub = await connectHub({ key, name: 'Sigurd', room: 'friday' }); // room optional, see 4.2
console.log('I am player', hub.id, 'in room', hub.room, 'host?', hub.isHost);
// Every frame: send your own state (the module only sends it 20 times per second)
function onFrame() {
hub.sendState({ x: me.position.x, y: me.position.y, z: me.position.z, ry: me.rotation.y, hp: me.hp, anim: me.anim });
// Draw everyone else, smoothly interpolated 100 ms in the past
for (const p of hub.players.values()) {
const s = hub.interpolated(p.id);
if (!s) continue;
const avatar = avatars.get(p.id) ?? createAvatar(p.id, p.name);
avatar.position.set(s.x, s.y, s.z);
avatar.rotation.y = s.ry;
}
}
hub.on('join', (p) => console.log(p.name, 'joined'));
hub.on('leave', (p) => removeAvatar(p.id));
hub.on('ev:shoot', (d, from) => drawTracer(from, d));
hub.emit('shoot', { ox, oy, oz, dx, dy, dz });
```
### Client module API
| Member | Description |
|---|---|
| `connectHub({ key, name, room?, maxPlayers?, url?, interpDelayMs = 100, sendHz = 20 })` | Connects and joins. Resolves with `hub` once `welcome` has arrived. Rejects with `err.code` (section 6). |
| `hub.id` | Your player id (number, unique on the server). |
| `hub.name`, `hub.room` | Your sanitized name and the room code you ended up in. |
| `hub.host`, `hub.isHost` | Id of the room host, and whether that's you (section 5.3). |
| `hub.players` | `Map<id, { id, name, state, samples }>` of the **other** players. `state` = newest raw state. |
| `hub.interpolated(id, angles?)` | The player's state `interpDelayMs` ago. Numbers are interpolated; keys in `angles` (default `ry, rx, rz, yaw, pitch`) wrap around correctly. Returns `null` before the first state arrives. |
| `hub.sendState(obj)` | Your own state (max 1 KB as JSON). Call as often as you like. |
| `hub.emit(event, data, { to?, echo? })` | Event to everyone else in the room, or only to player `to`. `echo:true` also delivers it to yourself. |
| `hub.shared` | Plain object with the room's shared state (kept in sync automatically). |
| `hub.set(key, value, { ifAbsent?, ref? })` / `hub.del(key)` | Change shared state (section 4.5). |
| `hub.kick(id)` | Host only. |
| `hub.serverNow()` | Synchronized server clock in ms. Use it for anything that must happen at the same moment for everyone. |
| `hub.rtt` | Round trip in ms (smoothed). |
| `hub.on(type, fn)` → unsubscribe function | Types: `join(p)`, `leave(p)`, `host(id)`, `event(e, d, from, time)`, `ev:<name>(d, from, time)`, `set(k, v, from, ref)`, `del(k, from)`, `denied(k, currentValue, ref)`, `snap(msg)`, `error(msg)`, `close(code, reason)`. |
| `hub.close()` | Leave. |
The module does not reconnect automatically. On `close`, show a "Reconnect" button that calls `connectHub` again
with the same room code.
## 4. Raw protocol (if you don't use the module)
WebSocket, **text frames with JSON**, one message per frame. Every message has a `t` (type) field.
Max 64 KB per message and max 300 messages per second per client (burst 600). Excess messages are dropped,
and a client that keeps flooding is disconnected.
### 4.1 Client → server
| `t` | Fields | Meaning |
|---|---|---|
| `hello` | `key`, `name`, `room?`, `maxPlayers?`, `sid?`, `v: 1` | Must be the first message, within 10 s. `sid` = a random id per browser tab (keep it in `sessionStorage`). If a connection with the same `sid` already exists in the project, the server closes the old one (`replaced`), so reconnects never leave a frozen duplicate player. The client module does this automatically. |
| `state` | `s` (object, ≤ 1 KB as JSON) | Your current state. Replaces the previous one. Send ≤ 20–30 times/s. |
| `ev` | `e` (string ≤ 32 chars), `d` (any JSON), `to?` (player id), `echo?` (bool) | Relay an event. |
| `set` | `k` (string ≤ 64), `v` (any JSON ≤ 2 KB), `ifAbsent?`, `ref?` | Set a key in the room's shared state. |
| `del` | `k` | Delete a key. |
| `kick` | `id` | Host only. |
| `ping` | `c` (any number, e.g. `performance.now()`) | Server answers `pong`. Allowed before `hello`. |
### 4.2 Rooms
- `room` omitted → **quick match**: you are put in the fullest open auto-room (code `auto-xxxx`), or a new one.
- `room: "friday"` → join that room, or create it if it doesn't exist. Code: 1–48 chars `A-Z a-z 0-9 _ -`.
Rooms are case-sensitive. Share the code with friends to play together.
- `maxPlayers` (optional) sets the room size when **you create it**, capped by the project limit (default 16).
- A room disappears when the last player leaves. All of its shared state disappears with it.
### 4.3 Server → client
| `t` | Fields | Meaning |
|---|---|---|
| `welcome` | `v, id, name, room, host, tick, time, maxPlayers, players: [{id, name, s}], state: {k: v}` | You are in. `players` = the others, `s` = their latest state or `null`. `state` = the shared state. |
| `snap` | `time`, `full`, `p: { "<id>": state, ... }` | 20 times/s. Contains only players whose state **changed** since the last snap. Once per second `full: true` includes everyone. Your own state is included too; ignore it. |
| `join` | `id, name` | Someone joined (no state yet). |
| `leave` | `id` | Someone left. |
| `host` | `id` | New host (the previous host left). |
| `ev` | `e, d, from, time` | Event from player `from`. |
| `set` | `k, v, from, ref` | Shared state changed (also sent to the one who set it, so it works as a confirmation). |
| `del` | `k, from` | Key deleted. |
| `denied` | `k, v, ref` | Your `set` with `ifAbsent` lost: the key already existed. `v` = current value. Only sent to you. |
| `pong` | `c, time` | `c` echoed back, `time` = server clock in ms. |
| `error` | `code, msg` | See section 6. |
All `time` values are server milliseconds (Unix epoch). Clock sync: `offset = time + rtt/2 − Date.now()`,
using the ping with the lowest `rtt` of the last few.
### 4.4 Interpolation (how to draw other players smoothly)
Store every `snap` sample per player as `{ time, s }`. When rendering, compute `t = serverNow − 100 ms`, find the
two samples around `t` and interpolate. That way other players move smoothly even though updates come only
20 times per second and the network jitters. Your **own** player is moved locally right away (never wait for the server).
### 4.5 Shared room state
A small key/value store per room that everyone sees. Good for things that must stay the same for everyone and
for players who join later: built walls, opened chests, match phase, zone, scores.
- `set` overwrites; the latest write wins. Every `set` is broadcast to everyone, including the sender.
- `ifAbsent: true` makes it "first come, first served": if the key already exists, nothing changes and only you get `denied`.
Use it for picking up items: `set('pickup:42', myId, { ifAbsent: true })`. Whoever gets the `set` back with
`from === myId` has the item.
- Max 500 keys per room and 2 KB per value. Use prefixes: `wall:<id>`, `chest:<id>`, `score:<playerId>`.
## 5. How to build a Fortnite-like game on top of it
The server trusts the clients. That's fine for a game among friends and keeps the client code simple.
### 5.1 What goes where
| Thing | Use | Example |
|---|---|---|
| Position, rotation, animation, HP, current weapon | `state` (each player sends their own) | `{x,y,z,ry,hp,anim:'run',w:'ar'}` |
| Shooting, hit, emote, sound | `ev` | `emit('shoot', {o:[x,y,z], d:[dx,dy,dz]})` |
| Damage to a specific player | `ev` with `to` | `emit('hit', {dmg: 20, head: false}, { to: targetId })` |
| Built walls/ramps, destroyed walls | shared state | `set('wall:'+id, {x,y,z,rot,type,hp})`, `del('wall:'+id)` |
| Loot and chests | shared state with `ifAbsent` | `set('loot:17', myId, {ifAbsent:true})` |
| Match phase, storm/zone, round start | shared state, written by the **host** | `set('match', {phase:'storm', startedAt: hub.serverNow()})` |
| Scoreboard | shared state | `set('score:'+hub.id, {kills, deaths})` |
### 5.2 Shooting and damage (recommended pattern)
1. The shooter does the hit test locally against the **interpolated** positions they see on screen.
That's what feels fair to the shooter.
2. Everyone gets an `ev` `shoot` so they can draw the tracer and play the sound.
3. On a hit, the shooter sends `ev` `hit` **to the victim only** (`to: victimId`) with the damage.
4. The **victim** subtracts the HP from its own state. At 0 HP it sends `ev` `died` `{by: shooterId}` to everyone
and updates the scores. HP lives in one place (the victim's own state), so it never gets out of sync.
### 5.3 The host
The first player in a room is the **host**. When the host leaves, the oldest remaining player takes over (`host` message).
The host is a good place for logic that only one player should run: start the round, shrink the storm, spawn loot,
run bots. Write the result to shared state (`set`), so everyone, including players who join later, sees the same thing.
Always check `hub.isHost` at the moment you act, and listen for `host`, because the role can move during a match.
### 5.4 Timing
Use `hub.serverNow()` for everything that has to happen at the same time for everyone. Example: the host writes
`set('storm', {startAt: hub.serverNow() + 30000, from: 200, to: 20, durationMs: 120000})`. Every client then
computes the storm radius itself from `serverNow()`, without more network traffic.
### 5.5 Keep it light
- Send `state` 20 times per second (the module does this for you). Round numbers to 2 decimals.
- Use short keys (`x`, `ry`, `hp`) rather than long names. 16 players × 20 Hz × 100 bytes ≈ 32 KB/s per player.
- Don't put big objects (maps, level data) in shared state. The level should be generated from a seed
(`set('seed', 12345)` from the host) or bundled with the game.
### 5.6 Your game already has PeerJS multiplayer? Add a hub transport instead of rewriting it
If the game already has a host/client network layer built on PeerJS (`new Peer(id)`, `peer.connect(hostId)`,
`peer.on('connection')`, `conn.send(obj)`, `conn.on('data' | 'open' | 'close')`), **keep all of that game code**
and only swap the transport. Write a small class with the same surface as the part of PeerJS the game uses,
and send everything through the hub as point-to-point events. Nothing else in the network code has to change.
- **Host:** `connectHub({ key, name, room: <the game's room code made ASCII, e.g. "sakura-kirsebaer-42"> })`.
The first one in the room becomes `hub.host`. If the room already has a host, the code is taken: pick another code.
- **Friend:** joins the same room. `peer.connect(hostId)` → `hub.emit('pj', { k: 'conn', cid }, { to: hub.host })`.
The host answers `{ k: 'acc', cid }`. Then both sides fire `open`.
- **`conn.send(obj)`** → `hub.emit('pj', { k: 'data', cid, d: obj }, { to: otherId })`. On receipt, call the connection's `data` handler with `d`.
- **`conn.close()`** → `{ k: 'close', cid }`. Also treat the hub's `leave` event for that player as `close`.
- **Errors:** `bad_key` / `room_full` / `closed` → map to the game's existing error texts (e.g. PeerJS `peer-unavailable`, `network`).
- Point-to-point `ev` doesn't go through the snapshot system, so the game's own snapshot format and rates stay as they are.
A host sending its own per-friend snapshots 15 times/s to 7 friends is about 105 messages/s, within the limit (300/s).
- One message may be up to 64 KB. That's enough for a start message with all the loot on the map. Keep regular snapshots small (a few KB).
- If the game has a test transport that relays messages (e.g. a `RelayPeer` used with `?tr=relay`), copy its structure.
It already does exactly this mapping. Select the new transport with e.g. `?tr=hub`, and make it the default once it works.
> Multiplayer can't work inside a claude.ai artifact preview, because the sandbox blocks network connections to other
> servers. Play it from the game's own address instead (e.g. **https://sakura.4p.dk/**, see `https://hub.4p.dk/deploy.md`).
## 6. Errors
| `code` | Meaning | What to do |
|---|---|---|
| `bad_key` | Unknown key | Ask the player for the key again. |
| `rate_limited` | Too many wrong keys | Wait 5 minutes. |
| `room_full` | Room is full | Pick another room or quick match. |
| `project_full` | Too many players in the project in total | Try again later. |
| `too_many_rooms` | Too many open rooms in the project | Join an existing room. |
| `bad_room` | Invalid room code | 1–48 chars `A-Z a-z 0-9 _ -`. |
| `hello_timeout` | No `hello` within 10 s | Send `hello` right after connecting. |
| `state_too_big`, `value_too_big`, `too_many_keys` | Limits exceeded | Send less data. The connection stays open. |
| `not_host`, `not_joined`, `already_joined`, `bad_json`, `unknown_type` | Protocol errors | Fix the code. |
| `kicked` | The host kicked you | |
| `replaced` | The same tab connected again (double click, reconnect) | Nothing; the newer connection is the one in use. Don't auto-reconnect on this code. |
WebSocket close codes: `4000` fatal error (see the `error` before it), `4003` key revoked, `4004` kicked, `4005` replaced by a newer connection from the same tab, `4008` flooding.
## 7. Limits (default per project, can be raised by the server owner)
| | Default |
|---|---|
| Players per room | 16 |
| Open rooms | 20 |
| Connected clients in total | 64 |
| Snapshot rate | 20 Hz |
| Message size | 64 KB |
| `state` size | 1 KB |
| Shared state | 500 keys × 2 KB |
| Messages per second per client | 300 (burst 600) |
The server is a small shared VPS in Germany. It's meant for playing with friends and family, not for a public launch.
## 8. Testing
1. Open `https://hub.4p.dk/test.html` in two browser tabs, type the key and the same room code,
and move the dots with the arrow keys. If they move in both tabs, the key and the server work.
2. In your own game: open two tabs (or two computers) with the same room code.
3. `GET /stats` with header `x-hub-key` shows your rooms and who is in them.