From a1a81f58f219d16bfd21f50c5993072193bf4684 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Rapha=C3=ABl=20Jakse?= Date: Sat, 4 Apr 2020 16:19:57 +0200 Subject: [PATCH] Keep alive --- trivabble-server.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) 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]; -- 2.30.2