2019-01-12 11:43:36 +01:00
|
|
|
const dgram = require('dgram'),
|
2019-01-20 11:21:40 +01:00
|
|
|
HexUtil = require('./HexUtil'),
|
|
|
|
Logger = require('./Logger');
|
2019-01-12 11:43:36 +01:00
|
|
|
|
|
|
|
class GlobalUdpSocket {
|
|
|
|
constructor() {
|
|
|
|
this.socket = null;
|
|
|
|
this.callbacks = new Set();
|
2019-01-13 05:38:49 +01:00
|
|
|
this.debuggingCallbacks = new Set();
|
2019-01-20 11:21:40 +01:00
|
|
|
this.logger = new Logger();
|
2019-01-12 11:43:36 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
_getSocket() {
|
|
|
|
if (!this.socket) {
|
|
|
|
const udpSocket = this.socket = dgram.createSocket('udp4');
|
|
|
|
udpSocket.unref();
|
|
|
|
udpSocket.bind();
|
|
|
|
udpSocket.on('message', (buffer, rinfo) => {
|
2019-01-13 05:38:49 +01:00
|
|
|
const fromAddress = rinfo.address;
|
|
|
|
const fromPort = rinfo.port;
|
2019-01-20 11:21:40 +01:00
|
|
|
this.logger.debug(log => {
|
|
|
|
log(fromAddress + ':' + fromPort + " <--UDP");
|
|
|
|
log(HexUtil.debugDump(buffer));
|
|
|
|
});
|
2019-01-12 11:43:36 +01:00
|
|
|
for (const cb of this.callbacks) {
|
2019-01-13 05:38:49 +01:00
|
|
|
cb(fromAddress, fromPort, buffer);
|
2019-01-12 11:43:36 +01:00
|
|
|
}
|
|
|
|
});
|
2019-01-20 11:21:40 +01:00
|
|
|
udpSocket.on('error', e => {
|
|
|
|
this.logger.debug("UDP ERROR:", e);
|
2019-01-12 11:43:36 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
return this.socket;
|
|
|
|
}
|
|
|
|
|
|
|
|
send(buffer, address, port) {
|
|
|
|
this._getSocket().send(buffer,0,buffer.length,port,address);
|
|
|
|
}
|
|
|
|
|
2019-01-13 05:38:49 +01:00
|
|
|
addCallback(callback, debug) {
|
2019-01-12 11:43:36 +01:00
|
|
|
this.callbacks.add(callback);
|
2019-01-13 05:38:49 +01:00
|
|
|
if (debug) {
|
|
|
|
this.debuggingCallbacks.add(callback);
|
2019-01-20 11:21:40 +01:00
|
|
|
this.logger.debugEnabled = true;
|
2019-01-13 05:38:49 +01:00
|
|
|
}
|
2019-01-12 11:43:36 +01:00
|
|
|
}
|
|
|
|
removeCallback(callback) {
|
|
|
|
this.callbacks.delete(callback);
|
2019-01-13 05:38:49 +01:00
|
|
|
this.debuggingCallbacks.delete(callback);
|
2019-01-20 11:21:40 +01:00
|
|
|
this.logger.debugEnabled = this.debuggingCallbacks.size > 0;
|
2019-01-12 11:43:36 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = GlobalUdpSocket;
|