Adding UDP-Broadcast-Layer
This commit is contained in:
parent
b56a776a54
commit
bcec3b3a78
48
lib/communication/udpLayer.ts
Normal file
48
lib/communication/udpLayer.ts
Normal file
@ -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));
|
||||
}
|
||||
}
|
@ -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);
|
||||
|
Loading…
Reference in New Issue
Block a user