From: Raphaƫl Jakse Date: Sat, 4 Apr 2020 14:19:57 +0000 (+0200) Subject: Keep alive X-Git-Url: https://secure.softndesign.org/git/?a=commitdiff_plain;h=a1a81f58f219d16bfd21f50c5993072193bf4684;p=trivabble.git Keep alive --- diff --git a/trivabble-server.js b/trivabble-server.js index 933350c..85e887f 100644 --- a/trivabble-server.js +++ b/trivabble-server.js @@ -24,6 +24,7 @@ const port = 3000; const SAVE_TIMEOUT = 5000; +const KEEP_ALIVE = 30000; var http = require("http"); var fs = require("fs"); @@ -118,6 +119,27 @@ function writeResponse(responseAndIsES, data, terminate) { ? "data:" + data + "\n\n" : data.length + data ); + + if (!terminate) { + keepAlive(responseAndIsES); + } +} + +function stopKeepAlive(responseAndIsES) { + if (responseAndIsES.keepAliveTimeout) { + clearTimeout(responseAndIsES.keepAliveTimeout); + } +} + +function keepAlive(responseAndIsES) { + stopKeepAlive(responseAndIsES); + responseAndIsES.keepAliveTimeout = setTimeout(function () { + responseAndIsES[0].write( + responseAndIsES[1] + ? ":\n\n" + : "2[]" + ) + }, KEEP_ALIVE); } function newBoard() { @@ -220,8 +242,10 @@ Game.prototype.addListeningPlayer = function (playerName, responseAndIsES) { var that = this; that.listeningPlayers.push(responseAndIsES); + keepAlive(responseAndIsES); responseAndIsES[0].on("close", function () { + stopKeepAlive(responseAndIsES); var index = that.listeningPlayers.indexOf(responseAndIsES); if (index !== -1) { that.listeningPlayers[index] = that.listeningPlayers[that.listeningPlayers.length - 1];