node-gamedig/lib/GlobalUdpSocket.js

70 lines
2.2 KiB
JavaScript
Raw Normal View History

2019-01-12 11:43:36 +01:00
import { createSocket } from "dgram";
import { debugDump } from "./HexUtil.js";
import { promisify } from "util";
import Logger from "./Logger.js";
export default class GlobalUdpSocket {
constructor({port}) {
2019-01-12 11:43:36 +01:00
this.socket = null;
this.callbacks = new Set();
this.debuggingCallbacks = new Set();
2019-01-20 11:21:40 +01:00
this.logger = new Logger();
this.port = port;
2019-01-12 11:43:36 +01:00
}
async _getSocket() {
2019-01-12 11:43:36 +01:00
if (!this.socket) {
const udpSocket = createSocket({
type: 'udp4',
reuseAddr: true
});
2019-01-12 11:43:36 +01:00
udpSocket.unref();
udpSocket.on('message', (buffer, rinfo) => {
const fromAddress = rinfo.address;
const fromPort = rinfo.port;
2019-01-20 11:21:40 +01:00
this.logger.debug(log => {
log(fromAddress + ':' + fromPort + " <--UDP(" + this.port + ")");
log(debugDump(buffer));
2019-01-20 11:21:40 +01:00
});
for (const callback of this.callbacks) {
callback(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
});
await promisify(udpSocket.bind).bind(udpSocket)(this.port);
this.port = udpSocket.address().port;
this.socket = udpSocket;
2019-01-12 11:43:36 +01:00
}
return this.socket;
}
async send(buffer, address, port, debug) {
const socket = await this._getSocket();
if (debug) {
this.logger._print(log => {
log(address + ':' + port + " UDP(" + this.port + ")-->");
log(debugDump(buffer));
});
}
await promisify(socket.send).bind(socket)(buffer,0,buffer.length,port,address);
2019-01-12 11:43:36 +01:00
}
addCallback(callback, debug) {
2019-01-12 11:43:36 +01:00
this.callbacks.add(callback);
if (debug) {
this.debuggingCallbacks.add(callback);
2019-01-20 11:21:40 +01:00
this.logger.debugEnabled = true;
}
2019-01-12 11:43:36 +01:00
}
removeCallback(callback) {
this.callbacks.delete(callback);
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
}
}