2016-11-18 19 views
0

我有這個問題,如果我不能連接到主機,Nodejs攤位。奇怪的部分是,當它是一個數組並且端口是靜態的時,我使用async.eachSeries工作。有誰知道爲什麼?net.socket.setTimeout無法與async.eachOfSeries

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 
}); 

謝謝

約翰

回答

1

msn.com端口444連接失敗,最後「回調」(成功連接後)從未called-這就是爲什麼節點攤位。

檢查解決此問題的下面的代碼(注意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(); 
    }); 
}); 
+1

嗨RLaaa,非常感謝您的幫助。我確實有一些問題,如果'clearTimeout(timeout);'不在那裏,爲什麼會發生兩次回調?另外爲什麼我們想要添加var timeout;超出了異步的範圍?如果有一個閱讀資源,你可以指導我,這也適用於我。 – sonance207

+1

好評 - 因爲它不是真的有必要......我修改了代碼以反映這一點。 – RLaaa