forked from FoundKeyGang/FoundKey
fix: stop sending pings on every pong
This resulted in endless ping-pong traffic on the websocket, happening every interval of network latency to the server (e.g. for me, with 40ms latency to my server, it was about every 40ms). On my server this ended up taking about 20% of foundkey's CPU usage. Now, just send pings every 30s, and check if we have received any pong's in last 60 seconds to check that the connection is still alive. Changelog: Fixed
This commit is contained in:
parent
7a94e9f2d5
commit
296c40c5b4
1 changed files with 12 additions and 8 deletions
|
@ -44,18 +44,21 @@ export const initializeStreamingServer = (server: http.Server): void => {
|
||||||
const main = new Connection(socket, ev, user, app);
|
const main = new Connection(socket, ev, user, app);
|
||||||
|
|
||||||
// ping/pong mechanism
|
// ping/pong mechanism
|
||||||
let pingTimeout = null;
|
let pingTimeout: NodeJS.Timeout | null = null;
|
||||||
function startHeartbeat() {
|
let disconnectTimeout = setTimeout(() => {
|
||||||
if (pingTimeout) clearTimeout(pingTimeout);
|
socket.terminate();
|
||||||
|
}, 60 * SECOND);;
|
||||||
|
function sendPing() {
|
||||||
socket.ping();
|
socket.ping();
|
||||||
pingTimeout = setTimeout(() => {
|
pingTimeout = setTimeout(() => {
|
||||||
socket.terminate();
|
sendPing();
|
||||||
}, 30 * SECOND);
|
}, 30 * SECOND);
|
||||||
}
|
}
|
||||||
startHeartbeat();
|
function onPong() {
|
||||||
socket.on('ping', () => { startHeartbeat(); });
|
disconnectTimeout.refresh()
|
||||||
socket.on('pong', () => { startHeartbeat(); });
|
}
|
||||||
|
sendPing();
|
||||||
|
socket.on('pong', onPong);
|
||||||
|
|
||||||
// keep user "online" while a stream is connected
|
// keep user "online" while a stream is connected
|
||||||
const intervalId = user ? setInterval(() => {
|
const intervalId = user ? setInterval(() => {
|
||||||
|
@ -75,6 +78,7 @@ export const initializeStreamingServer = (server: http.Server): void => {
|
||||||
redisClient.off('message', onRedisMessage);
|
redisClient.off('message', onRedisMessage);
|
||||||
if (intervalId) clearInterval(intervalId);
|
if (intervalId) clearInterval(intervalId);
|
||||||
if (pingTimeout) clearTimeout(pingTimeout);
|
if (pingTimeout) clearTimeout(pingTimeout);
|
||||||
|
if (disconnectTimeout) clearTimeout(disconnectTimeout);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in a new issue