How to Build a Multiplayer Game Server with WebSockets
Multiplayer games rely on real-time, bidirectional communication between clients and a central server. WebSockets provide a persistent, low-latency channel that’s ideal for game state updates. In this tutorial, you’ll build a simple multiplayer game server using JavaScript and the ws library.
1. Choose Your Tech Stack
Use Node.js for the server and the ws WebSocket library. Install it: npm install ws. For the client, the native WebSocket API works in browsers.
2. Set Up a Basic WebSocket Server
Create a file server.js. Import and start a WebSocket server on a port:
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
Listen for the connection event. Each client gets its own ws object.
3. Handle Connections and Messages
Inside the connection callback, assign a unique player ID. Use a simple players object to store state:
const players = {};
server.on('connection', (ws) => {
const id = Date.now().toString();
players[id] = { id, x: 0, y: 0 };
ws.send(JSON.stringify({ type: 'init', id, state: players }));
ws.on('message', (data) => {
const msg = JSON.parse(data);
if (msg.type === 'move') {
players[id].x = msg.x;
players[id].y = msg.y;
broadcast({ type: 'update', id, x: msg.x, y: msg.y });
}
});
ws.on('close', () => {
delete players[id];
broadcast({ type: 'leave', id });
});
});
4. Broadcast State to All Players
Create a broadcast function that sends a JSON message to every connected client except the sender (if needed):
function broadcast(data, exclude = null) {
server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN && client !== exclude) {
client.send(JSON.stringify(data));
}
});
}
Now, when a player moves, all other players see the update in real time.
Conclusion
You now have a functional multiplayer game server. Expand it by adding game logic, authentication, or a database. Remember to handle networking errors and scale with rooms for larger games.