/** * @author Martin Karkowski * @email m.karkowski@zema.de * @create date 2020-11-06 08:52:42 * @modify date 2021-03-01 17:43:12 * @desc [description] */ import { EventEmitter } from "events"; import { Server } from "http"; import * as io from "socket.io"; import { getNopeLogger } from "../logger/getLogger"; import { Bridge } from "./bridge"; import { DebuggedEventLayer } from "./debugEventLayer"; /** * Communication Layer using IO-Sockets. * * @export * @class IoSocketServer * @implements {ICommunicationInterface} */ export class IoSocketServer extends Bridge { protected _socket: io.Server; protected _sockets: Set; /** * Creates an instance of IoSocketServer. * @param {number} port The Port, on which the Server should be hosted * @param {Server} [server] A Server shich should be used. (Otherwise a Server is created) * @memberof IoSocketServer */ constructor(public port: number, server?: Server) { super("individual","individual",true, getNopeLogger("io-socket-server", "info")); if (server) { this._socket = (io as any)(server); } else { this._socket = (io as any)(); } const _this = this; this.connected.setContent(false); // Add a default Event-Layer // Perhaps that can be removed. this.addLayer(new DebuggedEventLayer(new EventEmitter(), "individual","individual",null),false, true); this._logger.info( "waiting for connection. Listening on port: " + port.toString() ); this._socket.listen(port); this._socket.on("connection", (client) => { _this._logger.info("New Connection established: " + client.id); // Add the Elements to the Client _this._sockets.add(client); // Add the socket as new layer: const _layer = new DebuggedEventLayer(client, "individual","individual", getNopeLogger("io-client-" + client.id, "info")); _this.addLayer(_layer, true); // Subscribe to Loosing connection: client.on("disconnect", () => { _this._logger.info("Connection of : " + client.id + " lost."); _this._sockets.delete(client); _this.removeLayer(_layer); if (_this._sockets.size === 0) { _this.connected.setContent(false); _this._logger.warn("All Connections lost"); } }); _this.connected.forcePublish(); }); this._sockets = new Set(); } async dispose(){ // Dispose the Connection Flag. this.connected.dispose(); // Dispose every connection. for (const client of this._sockets){ client.disconnect(); } } }