kannon/classes/Client.js

93 lines
No EOL
2.3 KiB
JavaScript

const Heartbeat = require('./Heartbeat.js');
let clientId = -1;
class Client {
constructor(socket) {
clientId++;
this.id = clientId;
this.socket = socket;
this.heartbeat = new Heartbeat(this);
this.#listenForEvents();
}
getId() {
return this.id;
}
getAddress() {
return this.socket.remoteAddress;
}
getPort() {
return this.socket.remotePort;
}
getTag() {
return '[' + this.getId() + '] ' + this.getAddress() + ':' + this.getPort() + ' >>';
}
#listenForEvents() {
logger.debug(this.getTag() + ' connected to communication server...');
this.socket.on('close', () => {
this.#handleEventClose()
});
this.socket.on('end', () => {
this.#handleEventEnd()
});
this.socket.on('error', (error) => {
this.#handleEventError(error);
});
this.socket.on('data', (data) => {
this.#handleEventData(data, this.socket)
});
this.heartbeat.on('timeout', () => {
this.#handleEventHeartbeatTimeout();
});
this.heartbeat.on('network-statistics', (data) => {
this.#handleEventNetworkStatistics(data);
});
}
#handleEventClose() {
logger.debug(this.getTag() + ' closed socket to communication server');
server.removeClient(this);
}
#handleEventEnd() {
logger.debug(this.getTag() + ' ended socket to communication server');
this.destroy();
}
#handleEventError(error) {
if (error === undefined) {
return;
}
logger.debug(this.getTag() + ' encountered an error: ' + error);
}
async #handleEventData(data) {
eventparser.parse(data);
}
#handleEventHeartbeatTimeout() {
logger.warn(this.getTag() + ' heartbeat timed out');
this.destroy();
}
#handleEventNetworkStatistics(data) {
// logger.debug(this.getTag() + ' network statistics: ' + JSON.stringify(data));
}
destroy() {
this.heartbeat.destroy();
this.heartbeat.removeAllListeners('timeout');
this.heartbeat.removeAllListeners('latency');
this.socket.end();
this.socket.destroy();
}
}
module.exports = Client;