如何在node.js http模块中超时时发送响应

Jac*_*ack 2 sockets timeout http node.js

在nodejs.org socket.setTimeout上,它说

当触发空闲超时时,套接字将收到"超时"事件,但不会切断连接.

但是当我测试这样的代码时:

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);
Run Code Online (Sandbox Code Playgroud)

套接字在超时后立即关闭,并且没有数据被回复到浏览器.这与文件完全不同.这是一个错误还是在http模块下有任何技巧处理套接字?

Aar*_*ron 7

文档确实是正确的,但是看起来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);
Run Code Online (Sandbox Code Playgroud)