nope/lib/communication/IoSocketServer.ts

92 lines
2.7 KiB
TypeScript
Raw Normal View History

2020-08-23 07:21:03 +00:00
import { Server } from "http";
2020-09-10 16:21:01 +00:00
import * as io from 'socket.io';
import { Logger } from "winston";
import { ICommunicationInterface } from "../dispatcher/nopeDispatcher";
2020-09-10 16:21:01 +00:00
import { getLogger } from "../logger/getLogger";
2020-08-23 07:21:03 +00:00
2020-09-11 12:07:31 +00:00
/**
* Communication Layer using IO-Sockets.
*
* @export
* @class IoSocketServer
* @implements {ICommunicationInterface}
*/
export class IoSocketServer implements ICommunicationInterface {
2020-08-23 07:21:03 +00:00
protected _socket: io.Server
2020-09-10 16:21:01 +00:00
protected _sockets: Set<io.Socket>;
protected _funcs: Map<string, (...args: any[]) => void>;
2020-09-10 16:21:01 +00:00
protected _logger: Logger;
2020-08-23 07:21:03 +00:00
2020-09-11 12:07:31 +00:00
/**
* 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
*/
2020-09-10 16:21:01 +00:00
constructor(public port: number, server?: Server) {
if (server) {
2020-08-23 07:21:03 +00:00
this._socket = (io as any)(server);
} else {
this._socket = (io as any)();
}
2020-09-10 16:21:01 +00:00
this._logger = getLogger('info', 'IO-Socket');
this._socket.listen(port);
const _this = this;
this._socket.on('connection', (client) => {
_this._logger.debug('New Connection established: ' + client.id);
// Add the Elements to the Client
_this._sockets.add(client);
// Subscribe to Loosing connection:
client.on('disconnect', () => {
_this._logger.debug('Connection of : ' + client.id + ' lost.');
_this._sockets.delete(client);
});
for (const [id, _func] of _this._funcs) {
// Subscribe to the Events:
client.on(id, (...args) => {
_this._logger.debug('received content: ', ...args);
2020-09-10 16:21:01 +00:00
// Forward the Message.
_func(...args);
});
}
});
2020-09-10 16:21:01 +00:00
this._sockets = new Set();
this._funcs = new Map<string, (...args: any[]) => void>();
2020-08-23 07:21:03 +00:00
}
off(event: string, cb: (...args: any[]) => void) {
// Remove the Subscription from the Socket.
for (const socket of this._sockets) {
socket.off(event, cb);
}
// Remove the Function.
this._funcs.delete(event);
}
on(event: string, cb: (...args: any[]) => void) {
// Add the Subscription to the Sockets.
for (const socket of this._sockets) {
socket.on(event, cb);
}
2020-08-23 07:21:03 +00:00
// Store the Function
this._funcs.set(event, cb);
2020-08-23 07:21:03 +00:00
}
send(event: string, data: any): void {
this._logger.debug('sending data on: ' + event);
this._socket.emit(event, data);
2020-08-23 07:21:03 +00:00
}
}