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('timeout', () => { this.#handleEventTimeout(); }); this.socket.on('close', () => { this.#handleEventClose() }); this.socket.on('end', () => { this.#handleEventEnd() }); this.socket.on('data', (data) => { this.#handleEventData(data, this.socket) }); this.heartbeat.on('timeout', () => { this.#handleEventHeartbeatTimeout(); }); this.heartbeat.on('latency', (data) => { this.#handleEventLatency(data); }); } async #handleEventData(data, socket) { 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;