const WebSocket = require('ws'); const uuid = require('node-uuid'); const jsDir = `${__dirname}/server`; const Game = require(`${jsDir}/game.js`); const wss = new WebSocket.Server({ port: 8080 }); const DEBUG = true; const G = new Game(); // Global, for now. Is there a need for an instance? Ben 052220 const Server = { games: {}, messageOthers: (ws, message) => { DEBUG && console.log("Sending to other " + wss.clients.size + " clients.") wss.clients.forEach((client) => { if (client !== ws && client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(message)); } }); }, messageAll: (message) => { DEBUG && console.log("Sending to all " + wss.clients.size + " clients.") wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(JSON.stringify(message)); } }); }, onDisconnect: (ws) => { DEBUG && console.log('Disconnected ' + ws.id); Server.messageOthers(ws, { head: { type: 'disconnect' }, body: { id: ws.id }}) DEBUG && console.log('Removing player: '); DEBUG && console.log(ws.id); G.removePlayer(ws.id); Server.messageOthers({ head: { type: 'players' }, body: G.getPlayers() }); }, onConnect: (ws, req) => { ws.id = uuid.v4(); DEBUG && console.log(req.url + ' connected ' + ws.id); ws.on('message', Server.onMessage.bind(null, ws)); ws.on('close', Server.onDisconnect.bind(null, ws)) Server.messageAll({ head: { type: 'connect' }, body: { id: ws.id }}); Server.messageAll({ head: { type: 'walls' }, body: G.getWalls()}) Server.messageAll({ head: { type: 'robots' }, body: G.getRobots()}) }, onMessage: (ws, json) => { const message = JSON.parse(json); DEBUG && console.log('Received message: '); DEBUG && console.log(message); if (!message.head || !message.body) { DEBUG && console.warn("Unprocessable message: ") DEBUG && console.warn(message); return; } switch (message.head.type) { case 'playerAdd': DEBUG && console.log('Adding player: '); DEBUG && console.log(ws.id); DEBUG && console.log(message.body); const santizedName = message.body.replace(/[^\w ]/g, ''); G.addPlayer(ws.id, santizedName); Server.messageAll({ head: { type: 'players' }, body: G.getPlayers() }); break; case 'playerRemove': break; default: console.warn("Unknown message type: ", message.head.type) } }, }; wss.on('connection', Server.onConnect); console.log("Websocket server listening on :8080")