/** * @author Martin Karkowski * @email m.karkowski@zema.de * @create date 2020-11-04 17:36:04 * @modify date 2021-03-19 14:35:58 * @desc [description] */ import * as io from "socket.io"; import { connect } from "socket.io-client"; import { generateId } from "../helpers/idMethods"; import { LoggerLevel } from "../logger/nopeLogger"; import { ICommunicationInterface } from "../types/nope/nopeCommunication.interface"; import { Bridge } from "./bridge"; import { EventLayer } from "./eventLayer"; import { MirrorLayer } from "./mirrorLayer"; /** * Communication Layer using IO-Sockets. * * @export * @class IoSocketServer * @implements {ICommunicationInterface} */ //@ts-ignore Ignore the Interface. Its implemented manually export class IoSocketClient extends Bridge implements ICommunicationInterface { 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 */ /** * Creates an instance of IoSocketClient. * @param {string} uri Uri of the Server. * @param {LoggerLevel} [level="info"] Logger level * @memberof IoSocketClient */ constructor( public uri: string, mode: "mirror" | "default" = "default", level: LoggerLevel = "info" ) { super(generateId(), "io-socket-client " + uri, level); // Make shure we use the http before connecting. this.uri = this.uri.startsWith("http://") ? this.uri : "http://" + this.uri; const _this = this; this.connected.getter = (value) => value; this.connected.setContent(false); this._logger.info("connecting to: " + uri); // 1. Create the Socket. const socket = connect(uri); // 2. Create the Layer. Based on the Mode it will be either an Mirror or Default Layer. const layer = mode === "default" ? new EventLayer(socket as any, this._logger) : new MirrorLayer(socket as any, this._logger); // 3. Add the Layer this.addLayer(layer); socket.on("connect", (...args) => { // Assign new ID. (_this._logger as any).context.name += "_" + socket.id; // Element is connected _this._logger.info("connected"); _this.connected.setContent(true); }); socket.on("disconnect", () => { // Connection Lost. _this._logger.error("Connection lost!"); _this.connected.setContent(false); }); } }