kannon-client/classes/Connection.js

113 lines
3 KiB
JavaScript
Raw Permalink Normal View History

2022-04-14 14:25:48 +02:00
const util = require('../libs/util.js');
const net = require('net');
const Heartbeat = require('./Heartbeat.js');
const Audiostream = require('./Audiostream.js');
class Connection {
constructor() {
if (util.isUnset(config.server.host)) {
logger.warn('host is not defined - defaulting to \'127.0.0.1\'...');
}
if (util.isUnset(config.server.port)) {
logger.warn('port is not defined - defaulting to \'3000\'...');
}
this.host = config?.server?.host || "127.0.0.1";
this.port = config?.server?.port || "3000";
this.audiostream = new Audiostream();
2022-04-14 14:25:48 +02:00
}
getHost() {
return this.host;
}
getPort() {
return this.port;
}
getTag() {
return this.getHost() + ':' + this.getPort();
}
initialize() {
return this.#handleSocket(net.connect({
host: this.host,
port: this.port
}));
}
#handleSocket(socket) {
return new Promise((resolve, reject) => {
socket.on('connect', () => {
this.#handleEventConnect(resolve, socket);
});
socket.on('error', (error) => {
this.#handleEventError(reject, error);
});
});
}
#handleEventConnect(resolve, socket) {
logger.info('connected to communication server \'' + this.getTag() + '\'...');
this.socket = socket;
this.heartbeat = new Heartbeat();
2022-04-14 14:25:48 +02:00
this.#handleHeartbeat();
socket.on('timeout', () => {
this.#handleEventTimeout();
});
socket.on('close', () => {
this.#handleEventClose(resolve);
});
socket.on('data', (data) => {
this.#handleEventData(data);
});
}
async #handleEventData(data) {
eventparser.parse(data);
2022-04-14 14:25:48 +02:00
}
#handleEventTimeout() {
logger.warn('connection to communication server \'' + this.getTag() + '\' timed out');
}
#handleEventError(reject, error) {
this.destroy();
return reject('error connecting to communication server \'' + this.getTag() + '\': ' + error);
}
#handleEventClose(resolve) {
logger.info('connection to communication server \'' + this.getTag() + '\' closed');
this.destroy();
return resolve();
}
#handleHeartbeat() {
this.heartbeat.on('timeout', () => {
logger.warn('heartbeat to communication server \'' + this.getTag() + '\' timed out');
});
}
destroy() {
if (this.heartbeat !== undefined) {
this.heartbeat.removeAllListeners();
2022-04-14 14:25:48 +02:00
this.heartbeat.destroy();
2022-04-20 16:15:51 +02:00
this.heartbeat = undefined;
2022-04-14 14:25:48 +02:00
}
if (this.socket !== undefined) {
this.socket.removeAllListeners();
2022-04-14 14:25:48 +02:00
this.socket.end();
this.socket.destroy();
this.socket = undefined;
}
if (this.audiostream !== undefined) {
this.audiostream.destroy();
}
2022-04-14 14:25:48 +02:00
}
}
module.exports = Connection;