diff --git a/lib/communication/udpLayer.ts b/lib/communication/udpLayer.ts new file mode 100644 index 0000000..2bb6e64 --- /dev/null +++ b/lib/communication/udpLayer.ts @@ -0,0 +1,48 @@ +import { createSocket, Socket } from 'dgram'; +import { Logger } from "winston"; +import { CommunicationEvents, ICommunicationInterface } from "../dispatcher/nopeDispatcher"; +import { getLogger } from "../logger/getLogger"; + +export class UdpSocket implements ICommunicationInterface { + + protected _socket: Socket + protected _funcs: Set<(...args: any[]) => void>; + protected _logger: Logger; + + constructor(public port: number) { + this._logger = getLogger('info', 'UDP-Socket'); + this._socket = createSocket('udp4') + this._socket.bind(port); + + const _this = this; + this._socket.on('message', (rawData) => { + try { + _this._logger.debug('New Data received'); + // Parse the Data: + const data = JSON.parse(rawData.toString('utf-8')); + // Forward the Message + for (const _func of _this._funcs) { + _func(data) + } + } catch (error) { + _this._logger.error('Error during receiving data'); + _this._logger.error(error) + } + }); + + this._socket.on('connect', () => { + + }) + + 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.send(JSON.stringify(data)); + } +} \ No newline at end of file diff --git a/test/testSocket.ts b/test/testSocket.ts index 43e4372..022e639 100644 --- a/test/testSocket.ts +++ b/test/testSocket.ts @@ -1,4 +1,5 @@ import { SocketBackend } from "../lib/communication/socketBackend"; +import { UdpSocket } from "../lib/communication/udpLayer"; import { getLinkedDispatcher } from "../lib/dispatcher/getLinkedDispatcher"; import { exportFunctionToDispatcher } from "../lib/dispatcher/nopeDispatcherDecorators"; import { generateBenchmarkFunction } from "../modules/funcs/generateBenchmarkFunction"; @@ -15,6 +16,6 @@ export const benchmark = exportFunctionToDispatcher(generateBenchmarkFunction(10 uri: 'benchmark' }) -const server = new SocketBackend(9002); - -const dispatcher = getLinkedDispatcher(server); +const serverIOSocket = new SocketBackend(9002); +const udpSocket = new UdpSocket(9000) +const dispatcher = getLinkedDispatcher(serverIOSocket);