nope/lib/communication/layers/IoSocketClient.ts
Martin Karkowski 9f44b24161 Updating lib
2021-11-12 08:57:03 +01:00

71 lines
2.0 KiB
TypeScript

/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
* @create date 2020-11-04 17:36:04
* @modify date 2021-11-10 16:52:36
* @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";
/**
* Communication Layer using IO-Sockets.
*
* @export
* @class IoSocketServer
* @implements {ICommunicationInterface}
*/
export class IoSocketClient extends Bridge implements ICommunicationInterface {
protected _socket: io.Server;
protected _sockets: Set<io.Socket>;
/**
* Creates an instance of IoSocketClient.
* @param {string} uri Uri of the Server.
* @param {LoggerLevel} [level="info"] Logger level
* @memberof IoSocketClient
*/
constructor(public uri: string, 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 = new EventLayer(socket as any, this._logger);
// 3. Add the Layer
this.addLayer(layer, true, true);
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);
});
}
}