From 448bd832a37ca1cf9a111386a92a64ae6c210352 Mon Sep 17 00:00:00 2001 From: Evert Prants Date: Sun, 25 Sep 2022 11:30:15 +0300 Subject: [PATCH] configurable websocket keepalive ping --- src/connector/websocket.connector.ts | 32 +++++++++++++++++----------- src/types/irc.interfaces.ts | 4 ++++ 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/connector/websocket.connector.ts b/src/connector/websocket.connector.ts index d72108d..23a50e1 100644 --- a/src/connector/websocket.connector.ts +++ b/src/connector/websocket.connector.ts @@ -31,10 +31,16 @@ export class IRCWebSocketConnector return new Promise((resolve, reject) => { const onConnect = () => { this.connected = true; - this.pingInterval = setInterval(() => { - this.lastPingName = Date.now().toString(); - this.write('PING :%s', this.lastPingName); - }, 60000); + + // 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); + }, (this.connOpts?.wsPingInterval as number) || 60000); + } + resolve(); }; @@ -64,16 +70,16 @@ export class IRCWebSocketConnector this.socket?.addEventListener('message', (event) => { const line = event.data.toString(); - if (line.indexOf('PING') === 0 && !this.connOpts?.skipPings) { - this.socket?.send('PONG' + line.substring(4)); - return; - } + // 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) - ) { - return; + if (line.includes('PONG') && line.includes(' :' + this.lastPingName)) { + return; + } } this.emit('data', line); diff --git a/src/types/irc.interfaces.ts b/src/types/irc.interfaces.ts index 744139c..870de52 100644 --- a/src/types/irc.interfaces.ts +++ b/src/types/irc.interfaces.ts @@ -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; }