kannon-client/classes/Heartbeat.js

54 lines
No EOL
1.5 KiB
JavaScript

const EventEmitter = require('events');
const Message = require('./Message.js');
class Heartbeat extends EventEmitter {
constructor(eventParser) {
super();
this.interval = config?.server?.heartbeat || 10000;
this.eventParser = eventParser;
this.#listenForPingPong();
this.#sendPing();
}
async #sendPing() {
if (this.timeout !== undefined) {
clearTimeout(this.timeout);
}
if (this.alive === false) {
this.emit('timeout');
return;
} else if (this.alive === undefined) {
await new Promise((resolve, reject) => {
setTimeout(resolve, this.interval);
})
}
this.alive = false;
await new Message('ping').send();
this.timeout = setTimeout(() => {
this.#sendPing();
}, this.interval);
}
async #listenForPingPong() {
this.eventParser.on('ping', () => {
logger.debug('handling event \'ping\', responding with \'pong\'...');
new Message('pong').send();
});
this.eventParser.on('pong', () => {
logger.debug('handling event \'pong\'...');
this.alive = true;
});
}
destroy() {
if (this.timeout !== undefined) {
clearTimeout(this.timeout);
}
this.eventParser.removeAllListeners('ping');
this.eventParser.removeAllListeners('pong');
}
}
module.exports = Heartbeat;