node-gamedig/lib/index.js

65 lines
1.5 KiB
JavaScript
Raw Normal View History

2013-07-10 12:02:48 +02:00
var dgram = require('dgram'),
EventEmitter = require('events').EventEmitter,
util = require('util'),
dns = require('dns'),
TypeResolver = require('./typeresolver');
2013-07-10 12:02:48 +02:00
var activeQueries = [];
var udpSocket = dgram.createSocket('udp4');
udpSocket.unref();
udpSocket.bind(21943);
udpSocket.on('message', function(buffer, rinfo) {
2014-02-02 12:32:02 +01:00
if(Gamedig.debug) console.log(rinfo.address+':'+rinfo.port+" <--UDP "+buffer.toString('hex'));
2013-07-10 12:02:48 +02:00
for(var i = 0; i < activeQueries.length; i++) {
var query = activeQueries[i];
if(
query.options.address != rinfo.address
&& query.options.altaddress != rinfo.address
) continue;
2013-07-10 13:07:13 +02:00
if(query.options.port != rinfo.port) continue;
2013-07-10 12:02:48 +02:00
query._udpResponse(buffer);
break;
}
});
udpSocket.on('error', function(e) {
if(Gamedig.debug) console.log("UDP ERROR: "+e);
});
2013-07-10 12:02:48 +02:00
Gamedig = {
2013-07-10 12:02:48 +02:00
query: function(options,callback) {
if(callback) options.callback = callback;
2013-07-10 12:02:48 +02:00
var query = TypeResolver(options.type);
if(!query) {
process.nextTick(function() {
callback({error:'Invalid server type: '+options.type});
});
return;
}
query.debug = Gamedig.debug;
2013-07-10 12:02:48 +02:00
query.udpSocket = udpSocket;
query.type = options.type;
// copy over options
for(var i in options) query.options[i] = options[i];
2013-07-10 12:02:48 +02:00
activeQueries.push(query);
2013-07-10 12:06:44 +02:00
query.on('finished',function(state) {
2013-07-10 12:02:48 +02:00
var i = activeQueries.indexOf(query);
if(i >= 0) activeQueries.splice(i, 1);
});
process.nextTick(function() {
query.start();
});
return query;
}
};
module.exports = Gamedig;