nope/lib/communication/udpLayer.ts
2020-09-11 08:30:45 +02:00

48 lines
1.5 KiB
TypeScript

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));
}
}