nope/lib/communication/layers/IoSocketClient.ts

72 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-11-04 16:39:20 +00:00
/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
* @create date 2020-11-04 17:36:04
2021-03-19 18:17:39 +00:00
* @modify date 2021-03-19 14:35:58
2020-11-04 16:39:20 +00:00
* @desc [description]
*/
import * as io from "socket.io";
import { connect } from "socket.io-client";
2021-03-22 19:24:15 +00:00
import { generateId } from "../../helpers/idMethods";
import { LoggerLevel } from "../../logger/nopeLogger";
import { ICommunicationInterface } from "../../types/nope/nopeCommunication.interface";
import { Bridge } from "../bridge";
2021-03-19 18:17:39 +00:00
import { EventLayer } from "./eventLayer";
/**
* 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<io.Socket>;
2021-03-19 18:17:39 +00:00
/**
* Creates an instance of IoSocketClient.
* @param {string} uri Uri of the Server.
* @param {LoggerLevel} [level="info"] Logger level
* @memberof IoSocketClient
*/
2021-03-22 19:24:15 +00:00
constructor(public uri: string, level: LoggerLevel = "info") {
2021-03-19 18:17:39 +00:00
super(generateId(), "io-socket-client " + uri, level);
2020-12-30 18:53:33 +00:00
// 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);
2021-03-19 18:17:39 +00:00
// 1. Create the Socket.
const socket = connect(uri);
2021-03-19 18:17:39 +00:00
// 2. Create the Layer. Based on the Mode it will be either an Mirror or Default Layer.
2021-03-22 19:24:15 +00:00
const layer = new EventLayer(socket as any, this._logger);
2021-03-19 18:17:39 +00:00
// 3. Add the Layer
2021-03-22 18:02:24 +00:00
this.addLayer(layer, true, true);
2020-12-30 18:53:33 +00:00
socket.on("connect", (...args) => {
2021-03-19 18:17:39 +00:00
// Assign new ID.
(_this._logger as any).context.name += "_" + socket.id;
// Element is connected
_this._logger.info("connected");
2021-03-19 18:17:39 +00:00
_this.connected.setContent(true);
});
2021-03-19 18:17:39 +00:00
socket.on("disconnect", () => {
// Connection Lost.
_this._logger.error("Connection lost!");
_this.connected.setContent(false);
});
}
2020-12-30 18:53:33 +00:00
}