简体   繁体   English

降低Node.js套接字连接的超时

[英]Lower timeout for Node.js socket connection

I want to verify using Node.js whether a certain port is reachable or not. 我想使用Node.js验证某个端口是否可访问。 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. PS:我知道Node.js中有用于套接字的setTimeout函数,但是它不是我想的那样,或者我使用的是错误的。

Add this lines for handle timeout: 添加以下行以处理超时:

client.setTimeout(1000);
client.on('timeout', function(){
  client.end();
})'

or: 要么:

client.setTimeout(1000, function(){
  client.end();
});

Docs: here 文件: 在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM