aboutsummaryrefslogtreecommitdiffstats
path: root/lib/sockets.js
diff options
context:
space:
mode:
authorAdam Soltys <[email protected]>2022-07-26 23:24:58 -0700
committerAdam Soltys <[email protected]>2022-08-01 22:18:18 -0700
commit23511ec1018ba30b32974ef6cdd6619b59fa00f9 (patch)
tree5b302d45c1b44a03714f7a7bc44b2a4cac96fbc3 /lib/sockets.js
parent816e0a79fe172980ac1c9c0055e8a0166a95e0e5 (diff)
downloadcoinos-server-23511ec1018ba30b32974ef6cdd6619b59fa00f9.tar.gz
coinos-server-23511ec1018ba30b32974ef6cdd6619b59fa00f9.zip
socket error logging
Diffstat (limited to 'lib/sockets.js')
-rw-r--r--lib/sockets.js12
1 files changed, 7 insertions, 5 deletions
diff --git a/lib/sockets.js b/lib/sockets.js
index e216d904..c80935d9 100644
--- a/lib/sockets.js
+++ b/lib/sockets.js
@@ -2,6 +2,7 @@ const jwt = require("jsonwebtoken");
const { v4: uuidv4 } = require("uuid");
const WebSocket = require("ws");
const { differenceInSeconds, subSeconds } = require("date-fns");
+const code = 1000;
wss = new WebSocket.Server({ clientTracking: false, noServer: true });
@@ -64,7 +65,7 @@ setInterval(() => {
for (const id in sockets[username]) {
let ws = sockets[username][id];
ws.beats++;
- if (ws.beats > 10) ws.close();
+ if (ws.beats > 10) ws.close(code, "too many beats");
}
}
}, 2000);
@@ -97,7 +98,7 @@ wss.on("connection", function(ws, req) {
lastSeen[token] = new Date();
try {
- if (!token || token === "null" || !jwt.decode(token)) return ws.close();
+ if (!token || token === "null" || !jwt.decode(token)) return ws.close(code, `bad token ${token}`);
const username = jwt.decode(token).username;
if (!username) throw new Error("Invalid JWT token");
@@ -107,7 +108,7 @@ wss.on("connection", function(ws, req) {
const p = existing.find(sid => sid !== id);
sockets[username][p].send(JSON.stringify({ type: "logout" }));
setTimeout(() => {
- if (sockets[username][p]) sockets[username][p].close();
+ if (sockets[username][p]) sockets[username][p].close(code, "too many sockets");
}, 5000);
}
sockets[username][id] = ws;
@@ -151,7 +152,7 @@ wss.on("connection", function(ws, req) {
}
if (e.message.includes("not found"))
ws.send(JSON.stringify({ type: "logout" }));
- setTimeout(() => ws && ws.close(), 1000);
+ setTimeout(() => ws && ws.close(code, `closing due to error ${e.message}`), 1000);
}
break;
case "token":
@@ -186,7 +187,8 @@ wss.on("connection", function(ws, req) {
}
});
- ws.on("close", function() {
+ ws.on("close", function(code, reason) {
+ if (reason) console.log("closing socket", reason);
try {
const username = names[id];
if (sockets[username] && sockets[username][id]) {