You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

59 lines
1.7 KiB

const WebSocket = require('ws');
const uuid = require('node-uuid');
const jsDir = `${__dirname}/`;
const Game = require(`${jsDir}/game.js`);
const wss = new WebSocket.Server({ port: 8080 });
const DEBUG = true;
// 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: (ws, 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("Closing " + ws.id)
Server.messageOthers(ws, { head: { type: 'disconnect' }, body: { id: ws.id }})
},
onConnect: (ws, req) => {
ws.id = uuid.v4();
DEBUG && console.log(req.url + ' connected to ' + ws.id);
ws.on('message', Server.onMessage.bind(null, ws));
ws.on('close', Server.onDisconnect.bind(null, ws))
const G = new Game();
Server.messageAll(ws, { head: { type: 'connect' }, body: { id: ws.id }});
Server.messageAll(ws, { head: { type: 'walls' }, body: G.walls})
},
onMessage: (ws, message) => {
DEBUG && console.log('Received: %s', message);
// Server.messageAll(ws, message);
},
};
wss.on('connection', Server.onConnect);
console.log("Websocket server listening on :8080")