rramsden
rramsden

Reputation: 123

How do i close a socket after a timeout in node.js?

I'm trying to close a socket after a connection times out after 1000ms. I am able to set a timeout that gets triggered after a 1000ms but I can't seem to destroy the socket... any ideas?

var connection = http.createClient(80, 'localhost');
var request = connection.request('GET', '/somefile.xml', {'host':'localhost'});
var start = new Date().getTime();

request.socket.setTimeout(1000);

request.socket.addListener("timeout", function() {
  request.socket.destroy();
  sys.puts("socket timeout connection closed");
});

request.addListener("response", function(response) {
  var responseBody = [];
  response.setEncoding("utf8");
  response.addListener("data", function(chunk) {
    sys.puts(chunk);
    responseBody.push(chunk);
  });

  response.addListener("end", function() {

  });
});

request.end();

returns

socket timeout connection closed
node.js:29
  if (!x) throw new Error(msg || "assertion error");
                ^
Error: assertion error
    at node.js:29:17
    at Timer.callback (net:152:20)
    at node.js:204:9

Upvotes: 1

Views: 5287

Answers (2)

chakrit
chakrit

Reputation: 61518

You might get better answers on the IRC channel #node.js on freenode. But AFAIK node isn't quite designed for canceling something mid-way. Mostly people just leave it dangling since, in node.js, there's no blocking I/O anyway.

I agree though, that there should be a way to cancel something mid-way, but I don't think you should mess with the request's internal socket connection. That's why you have the http.ClientRequest abstraction to manage the socket for you. The error could be because the timeout does works but that the request object weren't expecting the socket to already be closed.

Hope this helps.

Upvotes: 0

Related Questions