how to send reponse when timeout in node.js http m

2020-07-27 02:47发布

问题:

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:

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);