The server now sends regular ping requests to keep connections alive

This commit is contained in:
David Négrier 2020-10-15 13:52:19 +02:00
parent 49a0125f88
commit d098a1b8db
2 changed files with 35 additions and 12 deletions

View File

@ -60,6 +60,26 @@ function emitInBatch(socket: ExSocketInterface, payload: SubMessage): void {
socket.batchTimeout = null; socket.batchTimeout = null;
}, 100); }, 100);
} }
// If we send a message, we don't need to keep the connection alive
resetPing(socket);
}
/**
* Schedule a ping to keep the connection open.
* If a ping is already set, the timeout of the ping is reset.
*/
function resetPing(ws: ExSocketInterface): void {
if (ws.pingTimeout) {
clearTimeout(ws.pingTimeout);
}
ws.pingTimeout = setTimeout(() => {
if (ws.disconnecting) {
return;
}
ws.ping();
resetPing(ws);
}, 29000);
} }
export class IoSocketController { export class IoSocketController {
@ -232,6 +252,8 @@ export class IoSocketController {
// Let's join the room // Let's join the room
this.handleJoinRoom(client, client.position, client.viewport); this.handleJoinRoom(client, client.position, client.viewport);
resetPing(client);
}, },
message: (ws, arrayBuffer, isBinary): void => { message: (ws, arrayBuffer, isBinary): void => {
const client = ws as ExSocketInterface; const client = ws as ExSocketInterface;

View File

@ -19,6 +19,7 @@ export interface ExSocketInterface extends WebSocket, Identificable {
emitInBatch: (payload: SubMessage) => void; emitInBatch: (payload: SubMessage) => void;
batchedMessages: BatchMessage; batchedMessages: BatchMessage;
batchTimeout: NodeJS.Timeout|null; batchTimeout: NodeJS.Timeout|null;
pingTimeout: NodeJS.Timeout|null;
disconnecting: boolean, disconnecting: boolean,
tags: string[] tags: string[]
} }