I'm trying to set a timeout on an HTTP client that uses http.request with no luck. So far what I did is this:
var options = { ... }
var req = http.request(options, function(res) {
// Usual stuff: on(data), on(end), chunks, etc...
}
/* This does not work TOO MUCH... sometimes the socket is not ready (undefined) expecially on rapid sequences of requests */
req.socket.setTimeout(myTimeout);
req.socket.on('timeout', function() {
req.abort();
});
req.write('something');
req.end();
Any hints?
There is simpler method.
Instead of using setTimeout or working with socket directly,
We can use 'timeout' in the 'options' in client uses
Below is code of both server and client, in 3 parts.
Module and options part:
Server part:
Client part:
If you put all the above 3 parts in one file, "a.js", and then run:
then, output will be:
Hope that helps.
You should pass the reference to request like below
Request error event will get triggered
Curious, what happens if you use straight
net.sockets
instead? Here's some sample code I put together for testing purposes:Using your code, the issue is that you haven't waited for a socket to be assigned to the request before attempting to set stuff on the socket object. It's all async so:
The 'socket' event is fired when the request is assigned a socket object.
At this moment there is a method to do this directly on the request object:
This is a shortcut method that binds to the socket event and then creates the timeout.
Reference: Node.js v0.8.8 Manual & Documentation
Elaborating on the answer @douwe here is where you would put a timeout on a http request.
this.abort() is also fine.