简体   繁体   中英

How do I set a timeout for client http connections in node.js

I'm writing a node.js application that needs to talk to a server. It establishes an http connection with the following code:

var client = http.createClient(u.port, u.hostname, u.secure);
client.on("error", function(exception) {
    logger.error("error from client");
});
var request = client.request(method, u.path, headers);

I don't see any option in the node.js documentation for setting a timeout on the connection, and it seems to be set to 20 seconds by default. The problem I'm having is that I have users in China on what appears to be a slow or flaky network, who sometimes hit the timeout connecting to our datacenter in the US. I'd like to increase the timeout to 1 minute, to see if that fixes it for them.

Is there a way to do that in node.js?

Try

request.socket.setTimeout(60000); // 60 sec

I think you can do something like:

request.connection.setTimeout(60000)

request.connection returns the net.Stream object associated with the connection. and net.Stream has a setTimeout method.

There is no capability in Node to increase connect timeout. Since usually connect timeout (ie connection establishing timeout) is OS-wide setting for all applications (eg, 21 seconds in Windows , from 20 to 120 seconds in Linux ). See also Timouts in Request package .

In contrast, Node allows to set decreased timeout and abort connecting even in case when the connection is not yet established.

The further timeouts (in case of connection has been established) can be controlled according to the documentation (see request.setTimeout , socket.setTimeout ).

You have to wait for the client socket connection to be established first, before setting the timeout. To do this, add a callback for the 'socket' event:

req.on('socket', function (socket) {
    myTimeout = 500; // millis
    socket.setTimeout(myTimeout);  
    socket.on('timeout', function() {
        console.log("Timeout, aborting request")
        req.abort();
    });
}).on('error', function(e) {
    console.log("Got error: " + e.message);
    // error callback will receive a "socket hang up" on timeout
});

See this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM