Merge pull request #328 from thecodingmachine/ping

The server now sends regular ping requests to keep connections alive
This commit is contained in:
David Négrier 2020-10-15 14:12:12 +02:00 committed by GitHub
commit 3ba3b24647
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
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;
}, 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 {
@ -232,6 +252,8 @@ export class IoSocketController {
// Let's join the room
this.handleJoinRoom(client, client.position, client.viewport);
resetPing(client);
},
message: (ws, arrayBuffer, isBinary): void => {
const client = ws as ExSocketInterface;

View file

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