我遇到这个问题,如果我无法连接到主机,Nodejs 就会停止。奇怪的是,当它是一个数组并且端口是静态的时,我与 async.eachSeries 一起工作。有谁知道为什么吗?
client = new net.Socket;
hosts = {'google.com': '443', 'yahoo.com': '80','msn.com': '444'};
client.setTimeout(1000, function () {
console.log("Timeout has occurred")
});
async.eachOfSeries(hosts, function(port,host,callback) {
client.connect(port, host, function() {
console.log('Connected to ' + host + " on port " + port);
client.destroy();
callback();
});
});
client.on('timeout', function() {
console.log('client has timed out');
client.destroy(); // kill client after server's response
});
谢谢,
约翰
最佳答案
端口 444 上的 msn.com 连接失败,并且最后一个“回调”(成功连接后)永远不会被调用 - 这就是 Node 停止的原因。
检查下面的代码解决了这个问题(注意,msn 调用现在是第一个,只是超时了 - 我觉得这样更能说明流程)。
var async = require('async');
var net = require('net');
hosts = { 'msn.com': '444', 'google.com': '443', 'yahoo.com': '80' };
async.eachOfSeries(hosts, function (port, host, callback) {
client = new net.Socket;
client.setTimeout(1000, function () {
console.log("Timeout has occurred")
});
client.connect(port, host, function () {
console.log('Connected to ' + host + " on port " + port);
client.destroy();
callback();
}).on('timeout', function () {
console.log('client has timed out');
client.destroy();
callback();
});
});
关于javascript - net.socket.setTimeout 不适用于 async.eachOfSeries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40686063/