nope/lib/communication/IoSocketClient.ts
2020-12-05 02:28:33 +01:00

65 lines
1.9 KiB
TypeScript

/**
* @author Martin Karkowski
* @email m.karkowski@zema.de
* @create date 2020-11-04 17:36:04
* @modify date 2020-12-04 17:11:18
* @desc [description]
*/
import { EventEmitter } from "events";
import * as io from "socket.io";
import { connect } from "socket.io-client";
import { getNopeLogger } from "../logger/getLogger";
import { Bridge } from "./bridge";
import { EventLayer } from "./eventLayer";
/**
* Communication Layer using IO-Sockets.
*
* @export
* @class IoSocketServer
* @implements {ICommunicationInterface}
*/
export class IoSocketClient extends Bridge {
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("individual","individual",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 EventLayer(new EventEmitter(), "individual","individual",getNopeLogger("io-socket-server-internal")));
this.addLayer(new EventLayer(socket as any, "individual","individual",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);
});
}
}