net.socket.setTimeout 不适用于 async.eachOfSeries

net.socket.setTimeout does not work with async.eachOfSeries

我遇到了这个问题,如果我无法连接到主机,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
});

谢谢,

约翰

msn.com 端口 444 上的连接失败,最后一个 'callback'(连接成功后)永远不会被调用——这就是节点停止的原因。

检查以下解决此问题的代码(注意 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();
    });
});