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

Posted by rramsden on Stack Overflow See other posts from Stack Overflow or by rramsden
Published on 2010-05-21T23:15:54Z Indexed on 2012/09/26 3:38 UTC
Read the original article Hit count: 115

Filed under:

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

© Stack Overflow or respective owner

Related posts about node.js