Skip to content

Instantly share code, notes, and snippets.

@philk
Created May 4, 2012 17:47
Show Gist options
  • Select an option

  • Save philk/2596487 to your computer and use it in GitHub Desktop.

Select an option

Save philk/2596487 to your computer and use it in GitHub Desktop.
Test connection via node
var net = require('net');
function test_connection(addr, port, cb) {
var client = net.createConnection(port, addr);
var start = (new Date()).getTime();
client.on('connect', function () {
var end = (new Date()).getTime();
client.end();
client.destroy();
cb(null, (end - start));
});
client.on('error', function (err) {
client.end();
client.destroy();
cb(err, null);
});
client.on('timeout', function () {
client.destroy();
cb(new Error("Connection Timeout"));
});
};
test_connection("google.com", 80, function (err, time) {
if (err) { return console.error(err) };
console.log("Connected in " + time + "ms");
});
// Multiple could look something like this
var hosts = require('./some_config_file');
hosts.forEach(function (host) {
test_connection(host.addr, host.port, function (err, time) {
if (err) {
console.error("Host " + host.addr + " failed with error:", err);
now_panic_and_freak_out();
return null;
}
console.log("Connected in " + time + "ms");
report_success({address: host.addr, port: host.port, time: time});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment