nope/lib/communication/IoSocketClient.ts
Martin Karkowski 1e1e47aefe Fixing Layers
2021-03-12 08:57:02 +01:00

80 lines
2.1 KiB
TypeScript

/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
* @create date 2020-11-04 17:36:04
* @modify date 2021-03-01 17:41:45
* @desc [description]
*/
import { EventEmitter } from "events";
import * as io from "socket.io";
import { connect } from "socket.io-client";
import { getNopeLogger } from "../logger/getLogger";
import { ICommunicationInterface } from "../types/nope/nopeCommunication.interface";
import { Bridge } from "./bridge";
import { DebuggedEventLayer } from "./debugEventLayer";
/**
* 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>;
/**
* 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 uri: string) {
super(
false,
getNopeLogger("io-socket-client", "info")
);
// 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);
const socket = connect(uri);
// Add a default Event-Layer
// Perhaps that can be removed.
this.addLayer(
new DebuggedEventLayer(
new EventEmitter(),
this._logger
),
false,
true
);
this.addLayer(
new DebuggedEventLayer(socket as any, this._logger)
);
socket.on("connect", (...args) => {
// 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);
});
}
}