94 lines
No EOL
2.3 KiB
JavaScript
94 lines
No EOL
2.3 KiB
JavaScript
const Heartbeat = require('./Heartbeat.js');
|
|
const EventParser = require('./EventParser.js');
|
|
|
|
let clientId = -1;
|
|
|
|
class Client {
|
|
|
|
constructor(socket) {
|
|
clientId++;
|
|
this.id = clientId;
|
|
this.socket = socket;
|
|
this.eventParser = new EventParser();
|
|
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('timeout', () => {
|
|
this.#handleEventTimeout();
|
|
});
|
|
this.socket.on('close', () => {
|
|
this.#handleEventClose()
|
|
});
|
|
this.socket.on('end', () => {
|
|
this.#handleEventEnd()
|
|
});
|
|
this.socket.on('data', (data) => {
|
|
this.#handleEventData(data)
|
|
});
|
|
this.heartbeat.on('timeout', () => {
|
|
this.#handleEventHeartbeatTimeout();
|
|
});
|
|
this.heartbeat.on('latency', (data) => {
|
|
this.#handleEventLatency(data);
|
|
});
|
|
}
|
|
|
|
async #handleEventData(data) {
|
|
this.eventParser.parse(data);
|
|
}
|
|
|
|
#handleEventTimeout() {
|
|
logger.warn(this.getTag() + ' timed out');
|
|
this.destroy();
|
|
}
|
|
|
|
#handleEventHeartbeatTimeout() {
|
|
logger.warn(this.getTag() + ' heartbeat timed out');
|
|
this.destroy();
|
|
}
|
|
|
|
#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();
|
|
}
|
|
|
|
#handleEventLatency(data) {
|
|
this.latency = data;
|
|
logger.debug(this.getTag() + ' latency: ' + JSON.stringify(data));
|
|
}
|
|
|
|
destroy() {
|
|
this.heartbeat.destroy();
|
|
this.heartbeat.removeAllListeners('timeout');
|
|
this.heartbeat.removeAllListeners('latency');
|
|
this.socket.end();
|
|
this.socket.destroy();
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = Client; |