Created
May 4, 2012 17:47
-
-
Save philk/2596487 to your computer and use it in GitHub Desktop.
Test connection via node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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