2013-01-04 21:33:19 -05:00
|
|
|
var net = require('net')
|
|
|
|
, Client = require('./client')
|
2013-07-09 16:37:30 -04:00
|
|
|
, protocol = require('./protocol')
|
2013-12-30 10:05:22 -05:00
|
|
|
, states = protocol.states
|
2013-11-19 18:06:57 -05:00
|
|
|
;
|
2013-01-04 21:33:19 -05:00
|
|
|
|
|
|
|
module.exports = ping;
|
|
|
|
|
|
|
|
function ping(options, cb) {
|
|
|
|
var host = options.host || 'localhost';
|
|
|
|
var port = options.port || 25565;
|
|
|
|
|
|
|
|
var client = new Client();
|
|
|
|
client.on('error', function(err) {
|
|
|
|
cb(err);
|
|
|
|
});
|
2013-12-30 10:05:22 -05:00
|
|
|
|
|
|
|
client.once([states.STATUS, 0x00], function(packet) {
|
|
|
|
var data = JSON.parse(packet.response);
|
|
|
|
var start = Date.now();
|
|
|
|
client.once(0x01, function(packet) {
|
|
|
|
data.latency = Date.now() - start;
|
|
|
|
cb(null, data);
|
|
|
|
client.end();
|
|
|
|
});
|
|
|
|
client.write(0x01, { time: [0, 0]});
|
|
|
|
});
|
|
|
|
|
|
|
|
client.on('state', function(newState) {
|
|
|
|
if (newState === states.STATUS)
|
|
|
|
client.write(0x00, {});
|
|
|
|
});
|
|
|
|
|
2013-01-04 21:33:19 -05:00
|
|
|
client.on('connect', function() {
|
2013-12-30 10:05:22 -05:00
|
|
|
client.write(0x00, {
|
|
|
|
protocolVersion: 4,
|
|
|
|
serverHost: host,
|
|
|
|
serverPort: port,
|
|
|
|
nextState: 1
|
2013-07-07 05:04:15 -04:00
|
|
|
});
|
2013-12-30 10:05:22 -05:00
|
|
|
client.state = states.STATUS;
|
2013-01-04 21:33:19 -05:00
|
|
|
});
|
2013-01-27 18:56:59 -05:00
|
|
|
|
2013-01-04 21:33:19 -05:00
|
|
|
client.connect(port, host);
|
|
|
|
}
|