kannon/classes/Heartbeat.js

60 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();
2022-04-20 16:15:33 +02:00
this.interval = config?.heartbeat || 10000;
2022-04-14 14:23:41 +02:00
this.client = client;
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 sleep(this.interval);
}
this.alive = false;
await new Message('ping', { server: Date.now() }).send(this.client);
this.timeout = setTimeout(() => {
this.#sendPing();
}, this.interval);
}
async #listenForPingPong() {
2022-04-20 16:15:33 +02:00
eventparser.on('ping', () => {
2022-04-14 14:23:41 +02:00
logger.debug(this.client.getTag() + ' handling event \'ping\', responding with \'pong\'...');
new Message('pong').send(this.client);
});
2022-04-20 16:15:33 +02:00
eventparser.on('pong', (data) => {
2022-04-14 14:23:41 +02:00
logger.debug(this.client.getTag() + ' handling event \'pong\'...');
const now = Date.now();
this.alive = true;
this.emit('latency', {
toClient: (data.client - data.server),
fromClient: (now - data.client),
roundtrip: (now - data.server)
});
});
}
destroy() {
if (this.timeout !== undefined) {
clearTimeout(this.timeout);
}
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;