import { Server } from "http"; import * as io from 'socket.io'; import { Logger } from "winston"; import { ICommunicationInterface } from "../dispatcher/nopeDispatcher"; import { getLogger } from "../logger/getLogger"; /** * Communication Layer using IO-Sockets. * * @export * @class IoSocketServer * @implements {ICommunicationInterface} */ export class IoSocketServer implements ICommunicationInterface { protected _socket: io.Server protected _sockets: Set; protected _funcs: Map void>; protected _logger: Logger; /** * 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) { if (server) { this._socket = (io as any)(server); } else { this._socket = (io as any)(); } this._logger = getLogger('info', 'IO-Socket'); this._socket.listen(port); const _this = this; this._socket.on('connection', (client) => { _this._logger.debug('New Connection established: ' + client.id); // Add the Elements to the Client _this._sockets.add(client); // Subscribe to Loosing connection: client.on('disconnect', () => { _this._logger.debug('Connection of : ' + client.id + ' lost.'); _this._sockets.delete(client); }); for (const [id, _func] of _this._funcs) { // Subscribe to the Events: client.on(id, (...args) => { _this._logger.debug('received content: ', ...args); // Forward the Message. _func(...args); }); } }); this._sockets = new Set(); this._funcs = new Map void>(); } off(event: string, cb: (...args: any[]) => void) { // Remove the Subscription from the Socket. for (const socket of this._sockets) { socket.off(event, cb); } // Remove the Function. this._funcs.delete(event); } on(event: string, cb: (...args: any[]) => void) { // Add the Subscription to the Sockets. for (const socket of this._sockets) { socket.on(event, cb); } // Store the Function this._funcs.set(event, cb); } send(event: string, data: any): void { this._logger.debug('sending data on: ' + event); this._socket.emit(event, data); } }