85 lines
2.3 KiB
TypeScript
85 lines
2.3 KiB
TypeScript
/**
|
|
* @author Martin Karkowski
|
|
* @email m.karkowski@zema.de
|
|
* @create date 2020-11-06 08:52:42
|
|
* @modify date 2020-12-03 19:03:41
|
|
* @desc [description]
|
|
*/
|
|
|
|
import { EventEmitter } from "events";
|
|
import { Server } from "http";
|
|
import * as io from "socket.io";
|
|
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 IoSocketServer 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 port: number, server?: Server) {
|
|
super("individual","individual",true, getNopeLogger("io-socket-server", "info"));
|
|
|
|
if (server) {
|
|
this._socket = (io as any)(server);
|
|
} else {
|
|
this._socket = (io as any)();
|
|
}
|
|
|
|
const _this = this;
|
|
|
|
|
|
this.connected.setContent(false);
|
|
|
|
// Add a default Event-Layer
|
|
// Perhaps that can be removed.
|
|
this.addLayer(new EventLayer(new EventEmitter(), "individual","individual",getNopeLogger("io-socket-server-internal")),false);
|
|
|
|
this._logger.info(
|
|
"waiting for connection. Listening on port: " + port.toString()
|
|
);
|
|
|
|
this._socket.listen(port);
|
|
|
|
this._socket.on("connection", (client) => {
|
|
_this._logger.info("New Connection established: " + client.id);
|
|
|
|
// Add the Elements to the Client
|
|
_this._sockets.add(client);
|
|
|
|
// Add the socket as new layer:
|
|
const _layer = new EventLayer(client, "individual","individual");
|
|
_this.addLayer(_layer, true);
|
|
|
|
// Subscribe to Loosing connection:
|
|
client.on("disconnect", () => {
|
|
_this._logger.info("Connection of : " + client.id + " lost.");
|
|
_this._sockets.delete(client);
|
|
_this.removeLayer(_layer);
|
|
|
|
if (_this._sockets.size === 0) {
|
|
_this.connected.setContent(false);
|
|
_this._logger.warn("All Connections lost");
|
|
}
|
|
});
|
|
|
|
_this.connected.forcePublish();
|
|
});
|
|
|
|
this._sockets = new Set();
|
|
}
|
|
}
|