Strengthen WebSocket error handling
authorRaphaël Jakse <raphael.trivabble@jakse.fr>
Mon, 13 Apr 2020 19:18:40 +0000 (21:18 +0200)
committerRaphaël Jakse <raphael.trivabble@jakse.fr>
Mon, 13 Apr 2020 19:18:40 +0000 (21:18 +0200)
trivabble-server.js
trivabble.js

index c6e9deff9cbe7a5bfc648eb58a23335e75b05573..858ec7c65b24a3f8b2282dde3a7d73a444e3308c 100644 (file)
@@ -142,6 +142,10 @@ function Game() {
 }
 
 function writeMessage(responseAndType, data, terminate) {
+    if (!responseAndType[0]) {
+        return;
+    }
+
     if (responseAndType[1] === REQUEST_TYPE_WEBSOCKET) {
         webSocketWrite(responseAndType[0], data);
     } else {
@@ -189,7 +193,12 @@ function stop() {
             }
         }
 
-        console.log("Stopped", gamesCount, "games and", listeningPlayerCount, "player connections.");
+        console.log(
+            "Stopped", gamesCount, "game" + (gamesCount === 1 ? "" : "s"),
+            "and", listeningPlayerCount, "player connection" + (listeningPlayerCount === 1 ? "" : "s") +
+            "."
+        );
+
         server.close(saveGames);
     });
 }
@@ -329,6 +338,7 @@ Game.prototype.addListeningPlayer = function (playerName, responseAndType) {
 
         closed = true;
         stopKeepAlive(responseAndType);
+        responseAndType[0] = null;
 
         const index = that.listeningPlayers.indexOf(responseAndType);
         if (index !== -1) {
@@ -1019,11 +1029,18 @@ fs.readFile("games.backup.json", function (err, data) {
 
     // See https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers
     server.on("upgrade", function upgradeToWebsocket(request, socket) {
+        const responseAndType = [socket, REQUEST_TYPE_WEBSOCKET];
+
+        function closeSocket() {
+            responseAndType[0] = null;
+        }
+
         socket.on("error", function (e) {
-            console.error("Socket error", e);
+            console.error("Socket error", e.toString());
+            closeSocket();
         });
 
-        // socket.on("close", function () {});
+        socket.on("close", closeSocket);
 
         const webSocketMatch = request.url.match(/\/(?::[^/]+\/)?ws\/(?<data>[\s\S]+)$/u);
 
@@ -1080,8 +1097,6 @@ fs.readFile("games.backup.json", function (err, data) {
 
         debuglog("WS: established " + decodedData);
 
-        const responseAndType = [socket, REQUEST_TYPE_WEBSOCKET];
-
         let receivedBytes = null;
 
         socket.on("data", function webSocketData(buffer) {
index d5a644f9f244a3dbf91fc42ee55ad894258af0f0..3dc1dbae872bdd43f1abdcc3a4b73b9c2b13dc59 100644 (file)
@@ -31,7 +31,7 @@
     const POLLING_DELAY = 2000;
     const ENABLE_WEBSOCKETS = true;
     const ENABLE_EVENT_SOURCE = true;
-    const MAX_WEBSOCKET_ERRORS = 2;
+    const MAX_WEBSOCKET_ERRORS = 1;
 
     const _ = (window.libD && libD.l10n) ? libD.l10n() : function (s) {return s;};