2013-01-04 21:33:19 -05:00
|
|
|
var net = require('net')
|
|
|
|
, Client = require('./client')
|
2015-05-22 21:31:47 -04:00
|
|
|
, states = require('./transforms/serializer').states
|
2015-05-14 16:08:49 -04: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);
|
|
|
|
});
|
2015-05-14 16:08:49 -04:00
|
|
|
|
2015-09-14 13:07:25 -04:00
|
|
|
client.once('server_info', function(packet) {
|
2013-12-30 10:05:22 -05:00
|
|
|
var data = JSON.parse(packet.response);
|
|
|
|
var start = Date.now();
|
2015-09-14 13:07:25 -04:00
|
|
|
client.once('ping', function(packet) {
|
2013-12-30 10:05:22 -05:00
|
|
|
data.latency = Date.now() - start;
|
|
|
|
cb(null, data);
|
|
|
|
client.end();
|
|
|
|
});
|
2015-09-14 13:07:25 -04:00
|
|
|
client.write('ping', {time: [0, 0]});
|
2013-12-30 10:05:22 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
client.on('state', function(newState) {
|
2015-05-14 16:08:49 -04:00
|
|
|
if(newState === states.STATUS)
|
2015-09-14 13:07:25 -04:00
|
|
|
client.write('ping_start', {});
|
2013-12-30 10:05:22 -05:00
|
|
|
});
|
2015-05-14 16:08:49 -04:00
|
|
|
|
2013-01-04 21:33:19 -05:00
|
|
|
client.on('connect', function() {
|
2015-09-14 13:07:25 -04:00
|
|
|
client.write('set_protocol', {
|
2013-12-30 10:05:22 -05:00
|
|
|
protocolVersion: 4,
|
|
|
|
serverHost: host,
|
|
|
|
serverPort: port,
|
|
|
|
nextState: 1
|
2013-07-07 05:04:15 -04:00
|
|
|
});
|
2015-05-22 19:10:58 -04:00
|
|
|
client.state = states.STATUS;
|
2013-01-04 21:33:19 -05:00
|
|
|
});
|
2015-05-14 16:08:49 -04:00
|
|
|
|
2013-01-04 21:33:19 -05:00
|
|
|
client.connect(port, host);
|
|
|
|
}
|