如何在node.js http模块中超时时发送响应 [英] how to send reponse when timeout in node.js http module
问题描述
在nodejs.org socket.setTimeout 上,
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);
套接字在超时后立即关闭,并且没有数据回复浏览器.这与文档有很大的不同.这是一个错误还是在http模块下有任何技巧可以解决套接字?
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?
推荐答案
文档确实是正确的,但是看起来http
模块添加了一个调用socket.destroy()
的超时"侦听器.因此,您需要做的是通过调用request.socket.removeAllListeners('timeout')
摆脱该侦听器.
因此您的代码应如下所示:
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);
这篇关于如何在node.js http模块中超时时发送响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!