user3263650 user3263650 - 17 days ago 5
Javascript Question

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

I am having this issue were if I am not able to connect to a host, Nodejs stalls. The weird part is I had this working with async.eachSeries when it was a array and the port was static. Does anyone know why?

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


Thank you,

John

Answer

msn.com connection on port 444 fails and and the last 'callback' (after successful connect) is never called- which is why node stalls.

Check the following code which solves this (notice msn call is now the first one and just times out- I feel it's better for understating the flow). It's also important to clear the timeout after successfulconnection so callback won't be called twice.

var async = require('async');
var net = require('net');

hosts = { 'msn.com': '444', 'google.com': '443', 'yahoo.com': '80' };

var timeout;

async.eachOfSeries(hosts, function (port, host, callback) {
    client = new net.Socket;

    timeout = client.setTimeout(1000, function () {
        console.log("Timeout has occurred")
    });  

    client.connect(port, host, function () {
        clearTimeout(timeout);
        console.log('Connected to  ' + host + " on port " + port);
        client.destroy();
        callback();
    }).on('timeout', function () {
        console.log('client has timed out');
        client.destroy();
        callback();
    });
});