X-Git-Url: https://git.auder.net/?p=vchess.git;a=blobdiff_plain;f=server%2Fsockets.js;h=520b8b70753eac9aca1f301aab31d0aa79db4e0b;hp=4a61f685f4deb5443d9aa6457c50fd88c81c2b94;hb=7a0c1b7e33a346195caebfdfa6489e7c6d0457e6;hpb=2c9f08fce443d57a70e886242ec391d89e450a7b diff --git a/server/sockets.js b/server/sockets.js index 4a61f685..520b8b70 100644 --- a/server/sockets.js +++ b/server/sockets.js @@ -18,6 +18,12 @@ function send(socket, message) { socket.send(JSON.stringify(message)); } +// https://www.npmjs.com/package/ws - detect lost connections... +function noop() {} +function heartbeat() { + this.isAlive = true; +} + module.exports = function(wss) { // Associative array page --> sid --> tmpId --> socket // "page" is either "/" for hall or "/game/some_gid" for Game, @@ -30,11 +36,14 @@ module.exports = function(wss) { const discordClient = new Discord.Client(); let discordChannel = null; if (token.length > 0) { - discordClient.login(token).then( () => { + discordClient.login(token); + discordClient.once("ready", () => { discordChannel = discordClient.channels.cache.get(channel); }); } wss.on("connection", (socket, req) => { + socket.isAlive = true; + socket.on('pong', heartbeat); const query = getJsonFromUrl(req.url); const sid = query["sid"]; const id = query["id"]; @@ -217,22 +226,23 @@ module.exports = function(wss) { case "rematchoffer": case "draw": // "newgame" message can provide a page (corr Game --> Hall) + if (obj.code == "newchallenge") { + // Filter out targeted challenges and correspondance games: + if (!obj.data.to && obj.data.cadence.indexOf('d') < 0) { + const challMsg = ( + (obj.data.sender || "@nonymous") + " : " + + "**" + obj.data.vname + "** " + + "[" + obj.data.cadence + "] " + ); + if (!!discordChannel) discordChannel.send(challMsg); + else + // Log when running locally (dev, debug): + console.log(challMsg); + } + delete obj.data["sender"]; + } notifyRoom( obj.page || page, obj.code, {data: obj.data}, obj.excluded); - if ( - obj.code == "newchallenge" && - !obj.data.to && //filter out targeted challenges - obj.data.cadence.indexOf('d') < 0 //and correspondance games - ) { - const challMsg = ( - "New challenge: **" + obj.data.vname + "** " + - "[" + obj.data.cadence + "]" - ); - if (!!discordChannel) discordChannel.send(challMsg); - else - // Log when running locally (dev, debug): - console.log(challMsg); - } break; case "rnewgame": @@ -366,4 +376,15 @@ module.exports = function(wss) { socket.on("message", messageListener); socket.on("close", closeListener); }); + const interval = setInterval( + () => { + wss.clients.forEach(ws => { + if (ws.isAlive === false) return ws.terminate(); + ws.isAlive = false; + ws.ping(noop); + }); + }, + 30000 + ); + wss.on('close', () => clearInterval(interval)); }