我注意到,在某些情况下,节点服务器的net.createConnection()在触发错误之前会有很长的超时时间(这似乎是端口的一个特殊问题……)
我尝试连接到somedomain:9000 (监听、连接和正常工作)和somedomain:1234 (相同的域,不同的端口,等待大约2分钟,直到"connect ETIMEDOUT")
当我连接到不存在的域时,我立即得到一个错误,但如果我连接到可达主机上的不可达端口,则不会。我需要在<1秒内确定机器是否可访问。
我该怎么处理呢?一定有办法在不到2分钟的时间内发现一个无法访问的端口?至少某种类型的超时,只是在一段时间后将地址设置为无法访问?
谢谢
更新:当前连接代码:
this.openConnection = function() {
try {
console.log("[INFO] connecting to " + device.ip + ":" + device.port);
device.clientSocket = new net.createConnection(this.port,this.ip)
.on('connect', device.connected)
.on('data', device.inputReceived)
.on('error', function(err) {
if (err.code == "ENOTFOUND") {
console.log("[ERROR] No device found at this address!");
device.clientSocket.destroy();
return;
}
if (err.code == "ECONNREFUSED") {
console.log("[ERROR] Connection refused! Please check the IP.");
device.clientSocket.destroy();
return;
}
console.log("[CONNECTION] Unexpected error! " + err.message + " RESTARTING SERVER");
process.exit(1);
})
.on('disconnect', function() {
console.log("[CONNECTION] disconnected!");
});
} catch(err) {
console.log("[CONNECTION] connection failed! " + err);
}
};发布于 2015-03-31 11:24:55
当您连接时,您只需设置您自己的计时器来设置您想要的任何超时,如果在该计时器触发时连接没有成功,则它不会像您希望的那样快速成功。
这可以封装在单个函数中,只需一个回调或返回一个promise。
根据您的代码,下面是添加超时的尝试(未测试的代码):
this.openConnection = function(timeout) {
var timer;
timeout = timeout || 2000;
try {
console.log("[INFO] connecting to " + device.ip + ":" + device.port);
device.clientSocket = new net.createConnection(this.port,this.ip)
.on('connect', function() {
clearTimeout(timer);
device.connected();
})
.on('data', function() {
clearTimeout(timer);
device.inputReceived();
})
.on('error', function(err) {
clearTimeout(timer);
if (err.code == "ENOTFOUND") {
console.log("[ERROR] No device found at this address!");
device.clientSocket.destroy();
return;
}
if (err.code == "ECONNREFUSED") {
console.log("[ERROR] Connection refused! Please check the IP.");
device.clientSocket.destroy();
return;
}
console.log("[CONNECTION] Unexpected error! " + err.message + " RESTARTING SERVER");
process.exit(1);
})
.on('disconnect', function() {
console.log("[CONNECTION] disconnected!");
});
timer = setTimeout(function() {
console.log("[ERROR] Attempt at connection exceeded timeout value");
device.clientSocket.end();
}, timeout);
} catch(err) {
console.log("[CONNECTION] connection failed! " + err);
}
};https://stackoverflow.com/questions/29356800
复制相似问题