75 lines
2.2 KiB
TypeScript
75 lines
2.2 KiB
TypeScript
import { Server } from "http";
|
|
import * as io from 'socket.io';
|
|
import { Logger } from "winston";
|
|
import { CommunicationEvents, ICommunicationInterface } from "../dispatcher/nopeDispatcher";
|
|
import { getLogger } from "../logger/getLogger";
|
|
|
|
/**
|
|
* Communication Layer using IO-Sockets.
|
|
*
|
|
* @export
|
|
* @class IoSocketServer
|
|
* @implements {ICommunicationInterface}
|
|
*/
|
|
export class IoSocketServer implements ICommunicationInterface {
|
|
|
|
protected _socket: io.Server
|
|
protected _sockets: Set<io.Socket>;
|
|
protected _funcs: Set<(...args: any[]) => void>;
|
|
protected _logger: Logger;
|
|
|
|
/**
|
|
* 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) {
|
|
if (server) {
|
|
this._socket = (io as any)(server);
|
|
} else {
|
|
this._socket = (io as any)();
|
|
}
|
|
|
|
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);
|
|
});
|
|
|
|
// Forward the Messages
|
|
client.on('task', (...args) => {
|
|
|
|
_this._logger.debug('received content: ', ...args);
|
|
|
|
for (const _func of _this._funcs) {
|
|
_func(...args)
|
|
}
|
|
});
|
|
})
|
|
|
|
this._sockets = new Set();
|
|
this._funcs = new Set<(...args: any[]) => void>();
|
|
}
|
|
|
|
on(events: CommunicationEvents, cb: (...args: any[]) => void) {
|
|
this._funcs.add(cb);
|
|
}
|
|
|
|
send(data: any): void {
|
|
this._logger.debug('sending', data);
|
|
this._socket.emit('task', data);
|
|
}
|
|
} |