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?

4

1 に答える 1

9

ドキュメントは確かに正しいですが、httpモジュールが を呼び出す「タイムアウト」リスナーを追加しているようsocket.destroy()です。したがって、 を呼び出してそのリスナーを取り除く必要がありますrequest.socket.removeAllListeners('timeout')。したがって、コードは次のようになります。

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);
于 2013-01-02T14:11:31.007 に答える