From f6e13536853ca8e007e3100423afa75a369a90a4 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Rapha=C3=ABl=20Jakse?= Date: Mon, 13 Apr 2020 21:18:40 +0200 Subject: [PATCH] Strengthen WebSocket error handling --- trivabble-server.js | 25 ++++++++++++++++++++----- trivabble.js | 2 +- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/trivabble-server.js b/trivabble-server.js index c6e9def..858ec7c 100644 --- a/trivabble-server.js +++ b/trivabble-server.js @@ -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\/(?[\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) { diff --git a/trivabble.js b/trivabble.js index d5a644f..3dc1dba 100644 --- a/trivabble.js +++ b/trivabble.js @@ -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;}; -- 2.30.2