node-gamedig/lib/GlobalUdpSocket.js

53 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-01-12 11:43:36 +01:00
const dgram = require('dgram'),
HexUtil = require('./HexUtil');
class GlobalUdpSocket {
constructor() {
this.socket = null;
this.callbacks = new Set();
this.debuggingCallbacks = new Set();
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) => {
const fromAddress = rinfo.address;
const fromPort = rinfo.port;
if (this.debuggingCallbacks.size) {
console.log(fromAddress + ':' + fromPort + " <--UDP");
console.log(HexUtil.debugDump(buffer));
}
2019-01-12 11:43:36 +01:00
for (const cb of this.callbacks) {
cb(fromAddress, fromPort, buffer);
2019-01-12 11:43:36 +01:00
}
});
udpSocket.on('error', (e) => {
if (this.debuggingCallbacks.size) {
2019-01-12 11:43:36 +01:00
console.log("UDP ERROR: " + e);
}
});
}
return this.socket;
}
send(buffer, address, port) {
this._getSocket().send(buffer,0,buffer.length,port,address);
}
addCallback(callback, debug) {
2019-01-12 11:43:36 +01:00
this.callbacks.add(callback);
if (debug) {
this.debuggingCallbacks.add(callback);
}
2019-01-12 11:43:36 +01:00
}
removeCallback(callback) {
this.callbacks.delete(callback);
this.debuggingCallbacks.delete(callback);
2019-01-12 11:43:36 +01:00
}
}
module.exports = GlobalUdpSocket;