Keep alive

This commit is contained in:
Raphaël Jakse 2020-04-04 16:19:57 +02:00
parent 772646d940
commit a1a81f58f2
1 changed files with 24 additions and 0 deletions

View File

@ -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];