feat(net): server measures every player's ping and its own step cost, sent with each snapshot

Also fixes the ping message schema (it checked the field t, which is the message type).
This commit is contained in:
Benjamin Oezcan
2026-11-19 14:25:46 +01:00
parent 3dc770e34a
commit 593d69714b
6 changed files with 46 additions and 9 deletions

View File

@@ -7,15 +7,20 @@ const auth = require('../auth');
const HELLO_MS = 5000;
const RATE = 80; // messages per second per socket (inputs ~30/s + lobby)
const PING_MS = 15000;
const PING_MS = 2000; // ws ping every 2 s: keepalive + ping measurement
const DEAD_MS = 15000; // no pong for this long -> connection is dead
function attach(server, { lobby }) {
const wss = new WebSocketServer({ server, path: '/ws', maxPayload: RC.Proto.MAX_MSG });
wss.on('connection', ws => {
let user = null, tokens = RATE, last = Date.now();
ws.alive = true;
ws.on('pong', () => { ws.alive = true; });
ws.lastPong = Date.now();
ws.on('pong', () => {
ws.lastPong = Date.now();
if (ws.pingSent && user) lobby.setRtt(user.uid, Number(process.hrtime.bigint() - ws.pingSent) / 1e6);
ws.pingSent = 0n;
});
const send = msg => { if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(msg)); };
const bye = (code, reason) => { try { ws.close(code, reason); } catch (e) { /* closed */ } };
const helloTimer = setTimeout(() => { if (!user) bye(4001, 'HELLO_TIMEOUT'); }, HELLO_MS);
@@ -48,7 +53,10 @@ function attach(server, { lobby }) {
});
const beat = setInterval(() => {
for (const ws of wss.clients) { if (!ws.alive) { ws.terminate(); continue; } ws.alive = false; try { ws.ping(); } catch (e) { /* closed */ } }
for (const ws of wss.clients) {
if (Date.now() - ws.lastPong > DEAD_MS) { ws.terminate(); continue; }
try { ws.pingSent = process.hrtime.bigint(); ws.ping(); } catch (e) { /* closed */ }
}
}, PING_MS);
if (beat.unref) beat.unref();
wss.on('close', () => clearInterval(beat));