Implementing UDP/TCP Node.js backend skeleton
The plan is to build a Node.js game server with a UDP socket handling movement updates validated against a ring buffer of the last 30 frames and a TCP server handling chat/inventory messages and player connections. Player inputs are queued and processed each tick in a fixed-rate game loop that updates player states and broadcasts authoritative snapshots with acknowledgments for client reconciliation. The code will use JSON messaging and include key classes and data structures with explanatory comments.
/**
* server.js
*
* A simple multiplayer backend using:
* - UDP (dgram) for fast, lossy player movement updates.
* - TCP (net) for reliable chat/inventory messages.
*
* Implements a fixed-timestep game loop with client-side prediction /
* server reconciliation support by:
* - Tracking an authoritative frame number on the server.
* - Keeping a ring buffer of the last 30 frames (state snapshots).
* - Acknowledging the last processed client input sequence number in each snapshot.
*
* NOTE:
* This is a minimal example/skeleton. In production, you would want to:
* - Add authentication, validation, compression, rate limiting, etc.
* - Use a proper protocol instead of raw JSON for performance.
* - Handle NAT traversal, matchmaking, persistence, etc.
*/
const dgram = require('dgram');
const net = require('net');
const { v4: uuidv4 } = require('uuid');
const UDP_PORT = 41234;
const TCP_PORT = 41235;
const TICK_RATE = 20; // 20 ticks per second => 50 ms per tick
const FRAME_BUFFER_SIZE = 30;
const udpServer = dgram.createSocket('udp4');
const tcpServer = net.createServer();
// In-memory state
const players = new Map(); // id -> Player
const tcpClients = new Set(); // active TCP sockets (for chat/inventory)
let frameNumber = 0;
const frameBuffer = []; // ring buffer of last FRAME_BUFFER_SIZE frames
/**
* Player model
*/
class Player {
constructor(id, tcpSocket) {
this.id = id;
this.tcpSocket = tcpSocket;
this.udpEndpoint = null; // { address, port }
this.x = 0;
this.y = 0;
this.speed = 5; // units per second
this.pendingInputs = []; // { seq, timestamp, input: { dx, dy } }
this.lastProcessedInput = 0;
}
}
/**
* Handle TCP (chat + inventory) connections
*/
tcpServer.on('connection', socket => {
socket.setEncoding('utf8');
const playerId = uuidv4();
const player = new Player(playerId, socket);
players.set(playerId, player);
tcpClients.add(socket);
console.log(`TCP client connected: ${playerId}`);
// Send welcome message with playerId
socket.write(JSON.stringify({ type: 'welcome', playerId }) + '\n');
socket.on('data', data => {
// Allow multiple JSON messages separated by newline
data.toString().split('\n').filter(Boolean).forEach(str => {
try {
const msg = JSON.parse(str);
switch (msg.type) {
case 'chat':
handleChat(playerId, msg.text);
break;
case 'inventory':
handleInventory(playerId, msg.action, msg.item);
break;
case 'registerUdp':
// Client tells us its UDP endpoint
player.udpEndpoint = { address: msg.address, port: msg.port };
console.log(`Player ${playerId} registered UDP endpoint`, player.udpEndpoint);
break;
default:
console.warn(`Unknown TCP message type: ${msg.type}`);
}
} catch (err) {
console.error('Invalid TCP message', err);
}
});
});
socket.on('close', () => {
console.log(`TCP client disconnected: ${playerId}`);
tcpClients.delete(socket);
players.delete(playerId);
});
socket.on('error', err => {
console.error(`TCP client error: ${playerId}`, err);
});
});
function handleChat(playerId, text) {
console.log(`Chat from ${playerId}: ${text}`);
// Broadcast to all TCP clients
const payload = JSON.stringify({ type: 'chat', from: playerId, text }) + '\n';
tcpClients.forEach(client => {
client.write(payload);
});
}
function handleInventory(playerId, action, item) {
console.log(`Inventory action from ${playerId}: ${action} ${item}`);
// Stub: just echo back the action
const player = players.get(playerId);
if (player && player.tcpSocket) {
player.tcpSocket.write(JSON.stringify({
type: 'inventoryAck',
action,
item,
}) + '\n');
}
}
/**
* UDP server for movement updates
* Expected message format (JSON):
* {
* type: 'move',
* playerId: '...',
* seq: <number>, // incrementing sequence number for reconciliation
* timestamp: <number>, // client-side timestamp (ms)
* input: { dx: -1|0|1, dy: -1|0|1 } // movement direction
* }
*/
udpServer.on('message', (msg, rinfo) => {
let data;
try {
data = JSON.parse(msg.toString());
} catch (err) {
return console.error('Invalid UDP JSON');
}
if (data.type === 'move') {
const player = players.get(data.playerId);
if (!player) {
return; // unknown player
}
// Register UDP endpoint if not set or changed
player.udpEndpoint = { address: rinfo.address, port: rinfo.port };
// Validate timestamp within last FRAME_BUFFER_SIZE frames
const oldest = frameBuffer[0];
if (oldest && data.timestamp < oldest.timestamp) {
// too old -> drop to prevent time travel
return;
}
// queue the input for processing on the next tick
player.pendingInputs.push({
seq: data.seq,
timestamp: data.timestamp,
input: data.input,
});
}
});
/**
* Game simulation
*/
function applyInput(player, input, dt) {
// Basic movement integration using input.dx, input.dy normalized
const length = Math.hypot(input.dx, input.dy);
if (length > 0) {
const nx = input.dx / length;
const ny = input.dy / length;
player.x += nx * player.speed * dt;
player.y += ny * player.speed * dt;
}
}
function gameLoop() {
const now = Date.now();
frameNumber += 1;
const dt = 1 / TICK_RATE; // seconds per tick
// Process pending inputs
players.forEach(player => {
// Sort pending inputs by seq to ensure deterministic order
player.pendingInputs.sort((a, b) => a.seq - b.seq);
while (player.pendingInputs.length > 0) {
const inputMsg = player.pendingInputs.shift();
// extra validation: drop if timestamp is from the future
if (inputMsg.timestamp > now + 1000) continue;
applyInput(player, inputMsg.input, dt);
player.lastProcessedInput = inputMsg.seq;
}
});
// Snapshot current state into buffer
const snapshot = {
frame: frameNumber,
timestamp: now,
players: {},
};
players.forEach((p, id) => {
snapshot.players[id] = {
x: p.x,
y: p.y,
lastProcessedInput: p.lastProcessedInput,
};
});
frameBuffer.push(snapshot);
if (frameBuffer.length > FRAME_BUFFER_SIZE) {
frameBuffer.shift();
}
// Broadcast authoritative state to all players over UDP
broadcastState(snapshot);
}
function broadcastState(snapshot) {
const payload = Buffer.from(JSON.stringify({
type: 'state',
frame: snapshot.frame,
timestamp: snapshot.timestamp,
players: snapshot.players,
}));
players.forEach(player => {
if (player.udpEndpoint) {
udpServer.send(payload, player.udpEndpoint.port, player.udpEndpoint.address, err => {
if (err) console.error('UDP send error', err);
});
}
});
}
/**
* Start servers and simulation
*/
tcpServer.listen(TCP_PORT, () => {
console.log(`TCP server listening on port ${TCP_PORT}`);
});
udpServer.bind(UDP_PORT, () => {
console.log(`UDP server listening on port ${UDP_PORT}`);
});
// Fixed timestep loop
setInterval(gameLoop, 1000 / TICK_RATE);
/**
* --- CLIENT-SIDE (for illustration only; not part of the backend) ---
*
* Client-side prediction & reconciliation pseudocode:
*
* let predictedState = { x: 0, y: 0 };
* let inputSeq = 0;
* const pendingInputs = [];
*
* function sendInput(dx, dy) {
* inputSeq += 1;
* const msg = {
* type: 'move',
* playerId,
* seq: inputSeq,
* timestamp: Date.now(),
* input: { dx, dy },
* };
* udpSocket.send(JSON.stringify(msg));
*
* // Client-side prediction
* applyInputLocally(predictedState, msg.input, dt);
* pendingInputs.push(msg);
* }
*
* // When receiving server state:
* function onServerState(snapshot) {
* const serverPos = snapshot.players[playerId];
* predictedState.x = serverPos.x;
* predictedState.y = serverPos.y;
*
* // Drop all inputs the server has processed
* while (pendingInputs.length > 0 &&
* pendingInputs[0].seq <= serverPos.lastProcessedInput) {
* pendingInputs.shift();
* }
*
* // Re-apply pending inputs to predicted state
* pendingInputs.forEach(inputMsg => {
* applyInputLocally(predictedState, inputMsg.input, dt);
* });
* }
*/
How it works (server side):
- The TCP server accepts connections for reliable channels (chat, inventory). When a new TCP connection is established, a unique
playerId is created and sent to the client.
- The UDP server listens for movement update messages. Movement updates include a
seq (sequence number) and timestamp. The server keeps a ring buffer (frameBuffer) of the last 30 authoritative frames and drops movement inputs with timestamps older than the oldest frame to prevent “time travel”.
- On each simulation tick (
gameLoop), the server processes pending inputs for each player, updates positions, stores a snapshot in the ring buffer, and broadcasts the authoritative snapshot via UDP to all players. Each snapshot includes lastProcessedInput per player so clients can reconcile their prediction.
- Chat and inventory messages are handled over TCP. The code simply echoes acknowledgements for inventory and broadcasts chat to all connected TCP clients.
You can run this with node server.js. Clients would need to implement UDP movement messages with sequence numbers and timestamps, register their UDP endpoint via TCP, and implement client-side prediction and reconciliation as sketched in the pseudocode at the end.