kannon/classes/Heartbeat.js

62 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-04-14 14:23:41 +02:00
const sleep = require('../libs/util.js').sleep;
const EventEmitter = require('events');
const Message = require('./Message.js');
class Heartbeat extends EventEmitter {
constructor(client) {
super();
this.interval = config?.server?.heartbeat || 10000;
2022-04-14 14:23:41 +02:00
this.client = client;
this.#listenForPingPong();
this.#sendPing();
}
async #sendPing() {
if (this.destroyed === true) {
return;
}
2022-04-14 14:23:41 +02:00
if (this.timeout !== undefined) {
clearTimeout(this.timeout);
}
if (this.alive === false) {
this.emit('timeout');
}
if (this.alive === undefined) {
2022-04-14 14:23:41 +02:00
await sleep(this.interval);
}
this.alive = false;
2022-04-29 16:50:56 +02:00
this.ping = Date.now();
2022-04-21 13:09:31 +02:00
await new Message('ping').send(this.client);
await sleep(this.interval);
this.#sendPing();
2022-04-14 14:23:41 +02:00
}
async #listenForPingPong() {
2022-04-20 16:15:33 +02:00
eventparser.on('ping', () => {
2022-05-03 15:48:07 +02:00
logger.debug(this.client.getTag() + ' handling event \'ping\', responding with \'pong\'...');
2022-04-14 14:23:41 +02:00
new Message('pong').send(this.client);
});
2022-04-21 13:09:31 +02:00
eventparser.on('pong', () => {
2022-05-03 15:48:07 +02:00
logger.debug(this.client.getTag() + ' handling event \'pong\'...');
2022-04-14 14:23:41 +02:00
this.alive = true;
2022-04-29 16:50:56 +02:00
this.pong = Date.now();
2022-04-21 13:09:31 +02:00
this.latency = this.pong - this.ping;
this.emit('network-statistics', {
2022-04-29 16:50:56 +02:00
ping: this.ping,
pong: this.pong,
latency: this.latency
2022-04-14 14:23:41 +02:00
});
});
}
destroy() {
this.destroyed = true;
2022-04-20 16:15:33 +02:00
eventparser.removeAllListeners('ping');
eventparser.removeAllListeners('pong');
2022-04-14 14:23:41 +02:00
}
}
module.exports = Heartbeat;