kannon-client/classes/Heartbeat.js

49 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

const { sleep } = require('../libs/util.js');
2022-04-14 14:25:48 +02:00
const EventEmitter = require('events');
const Message = require('./Message.js');
class Heartbeat extends EventEmitter {
constructor() {
2022-04-14 14:25:48 +02:00
super();
this.interval = config?.server?.heartbeat || 10000;
this.#listenForPingPong();
this.#sendPing();
}
2022-04-14 14:25:48 +02:00
async #sendPing() {
if (this.destroyed === true) {
return;
2022-04-14 14:25:48 +02:00
}
if (this.alive === false) {
this.emit('timeout');
}
if (this.alive === undefined) {
await sleep(this.interval);
2022-04-14 14:25:48 +02:00
}
this.alive = false;
await new Message('ping').send();
await sleep(this.interval);
this.#sendPing();
2022-04-14 14:25:48 +02:00
}
async #listenForPingPong() {
eventparser.on('ping', () => {
2022-04-14 14:25:48 +02:00
logger.debug('handling event \'ping\', responding with \'pong\'...');
2022-04-21 13:40:00 +02:00
new Message('pong').send();
2022-04-14 14:25:48 +02:00
});
eventparser.on('pong', () => {
2022-04-14 14:25:48 +02:00
logger.debug('handling event \'pong\'...');
this.alive = true;
});
}
destroy() {
this.destroyed = true;
eventparser.removeAllListeners('ping');
eventparser.removeAllListeners('pong');
2022-04-14 14:25:48 +02:00
}
}
module.exports = Heartbeat;