Keep alive
authorRaphaël Jakse <raphael.jakse@univ-grenoble-alpes.fr>
Sat, 4 Apr 2020 14:19:57 +0000 (16:19 +0200)
committerRaphaël Jakse <raphael.jakse@univ-grenoble-alpes.fr>
Sat, 4 Apr 2020 14:30:44 +0000 (16:30 +0200)
trivabble-server.js

index 933350c61c4965f6d09354bc57a37053e2adccca..85e887f9d61415465c46ecc8b96b1e0ccbfd26a6 100644 (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];