Skip to content

Commit

Permalink
refactor: tweak types and checks for timeouts/intervals (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjie committed Nov 4, 2020
1 parent 74be9b8 commit 5cc9770
Showing 1 changed file with 31 additions and 31 deletions.
62 changes: 31 additions & 31 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -373,42 +373,42 @@ export function createServer(
// kick the client off (close socket) if the connection has
// not been initialised after the specified wait timeout
const connectionInitWait =
connectionInitWaitTimeout && // even 0 disables it
connectionInitWaitTimeout !== Infinity &&
setTimeout(() => {
if (!ctxRef.current.connectionInitReceived) {
ctxRef.current.socket.close(
4408,
'Connection initialisation timeout',
);
}
}, connectionInitWaitTimeout);
connectionInitWaitTimeout > 0 && isFinite(connectionInitWaitTimeout)
? setTimeout(() => {
if (!ctxRef.current.connectionInitReceived) {
ctxRef.current.socket.close(
4408,
'Connection initialisation timeout',
);
}
}, connectionInitWaitTimeout)
: null;

// keep alive through ping-pong messages
// read more about the websocket heartbeat here: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#Pings_and_Pongs_The_Heartbeat_of_WebSockets
let pongWait: NodeJS.Timeout | null;
let pongWait: NodeJS.Timeout | null = null;
const pingInterval =
keepAlive && // even 0 disables it
keepAlive !== Infinity &&
setInterval(() => {
// ping pong on open sockets only
if (socket.readyState === WebSocket.OPEN) {
// terminate the connection after pong wait has passed because the client is idle
pongWait = setTimeout(() => {
socket.terminate();
}, keepAlive);

// listen for client's pong and stop socket termination
socket.once('pong', () => {
if (pongWait) {
clearTimeout(pongWait);
pongWait = null;
}
});
keepAlive > 0 && isFinite(keepAlive)
? setInterval(() => {
// ping pong on open sockets only
if (socket.readyState === WebSocket.OPEN) {
// terminate the connection after pong wait has passed because the client is idle
pongWait = setTimeout(() => {
socket.terminate();
}, keepAlive);

// listen for client's pong and stop socket termination
socket.once('pong', () => {
if (pongWait) {
clearTimeout(pongWait);
pongWait = null;
}
});

socket.ping();
}
}, keepAlive);
socket.ping();
}
}, keepAlive)
: null;

function errorOrCloseHandler(
errorOrClose: WebSocket.ErrorEvent | WebSocket.CloseEvent,
Expand Down

0 comments on commit 5cc9770

Please sign in to comment.