在 nodejs.org 上 socket.setTimeout , 它说
When an idle timeout is triggered the socket will receive a 'timeout' event but the connection will not be severed.
但是当我这样测试代码时:
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);
超时后立即关闭socket,没有数据回复给浏览器。这与文档完全不同。这是一个错误还是在 http 模块下处理套接字有什么技巧?
最佳答案
文档确实是正确的,但是看起来 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);
关于node.js - 如何在 node.js http 模块超时时发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14121760/