I want to verify using Node.js whether a certain port is reachable or not. Basically, what I did is write the following program:
var net = require('net');
var client = new net.Socket();
client.connect(3003, 'localhost');
client.on('error', function (err) {
console.log(err);
process.exit();
});
client.once('connect', function () {
console.log('Connected!');
process.exit();
});
So far, this pretty much works fine. There is only one thing I'm not happy with, and that is the timeout handling. Locally it works as expected, but when I try
client.connect(81, 'www.google.de');
it takes up to two minutes until I get a timeout. Why is that happening, and what can I do against it?
PS: I know that there is the setTimeout function for sockets in Node.js, but either it does not what I think it should, or I am using it wrong.
Add this lines for handle timeout:
client.setTimeout(1000);
client.on('timeout', function(){
client.end();
})'
or:
client.setTimeout(1000, function(){
client.end();
});
Docs: here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.