2

On nodejs.org socket.setTimeout, it says

When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed.

But when I test code like this:

var http = require('http');

server = http.createServer(function (request, response) {
    request.socket.setTimeout(500);
    request.socket.on('timeout', function () {
        response.writeHead(200, {'content-type': 'text/html'});
        response.end('hello world');
        console.log('timeout');
    });
});

server.listen(8080);

The socket is closed immediately after timeout, and no data is replied to the browser. Which is quite different from the document. Is this a bug or is there any tricks dealing socket under http module?

1 Answer 1

9

The documentation is indeed correct, however it looks like the http module adds a 'timeout' listener which calls socket.destroy(). So what you need to do is get rid of that listener by calling request.socket.removeAllListeners('timeout'). So your code should look like:

var http = require('http');

server = http.createServer(function (request, response) {
    request.socket.setTimeout(500);
    request.socket.removeAllListeners('timeout'); 
    request.socket.on('timeout', function () {
        response.writeHead(200, {'content-type': 'text/html'});
        response.end('hello world');
        console.log('timeout');
    });
});

server.listen(8080);
1
  • This one creates a timeout on each request. It would be better if one common timeout could listen, and write the response on the socket.
    – Adam
    Oct 4, 2018 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.