configurable websocket keepalive ping

This commit is contained in:
Evert Prants 2022-09-25 11:30:15 +03:00
parent 2da387c427
commit 448bd832a3
Signed by: evert
GPG Key ID: 1688DA83D222D0B5
2 changed files with 23 additions and 13 deletions

View File

@ -31,10 +31,16 @@ export class IRCWebSocketConnector
return new Promise((resolve, reject) => {
const onConnect = () => {
this.connected = true;
// Allow using a custom pinger, otherwise, ping every minute
// to keep socket alive
if (!this.connOpts?.skipPings) {
this.pingInterval = setInterval(() => {
this.lastPingName = Date.now().toString();
this.write('PING :%s', this.lastPingName);
}, 60000);
}, (this.connOpts?.wsPingInterval as number) || 60000);
}
resolve();
};
@ -64,17 +70,17 @@ export class IRCWebSocketConnector
this.socket?.addEventListener('message', (event) => {
const line = event.data.toString();
if (line.indexOf('PING') === 0 && !this.connOpts?.skipPings) {
// Allow using a custom pinger
if (!this.connOpts?.skipPings) {
if (line.indexOf('PING') === 0) {
this.socket?.send('PONG' + line.substring(4));
return;
}
if (
line.indexOf('PONG') === 0 &&
line.includes(' :' + this.lastPingName)
) {
if (line.includes('PONG') && line.includes(' :' + this.lastPingName)) {
return;
}
}
this.emit('data', line);
});

View File

@ -144,6 +144,10 @@ export interface IIRCOptions {
* Special cases for included connections:
* - `path` - `IRCWebSocketConnector` will append this to the WebSocket URL.
* - `skipPings` - Included connectors will not respond to PINGs if set.
* - `wsPingInterval` - `IRCWebSocketConnector` pings the server instead of the server pinging it.
* Here, you can set the ping interval in milliseconds. Defaults to `60000`, 1 minute. This setting
* is ignored if you have specified `skipPings`, in which case, you will need to use a custom pinger
* for the WebSocket.
*/
connOpts?: Record<string, unknown>;
}