服务器在超时时没有响应就关闭套接字?"/>
为什么NodeJS http服务器在超时时没有响应就关闭套接字?
给出一个超时为10s的NodeJS http服务器:
const httpServer = require('http').createServer(app);
httpServer.timeout = 10 * 1000;
在超时时,邮递员显示此消息而没有任何响应代码:
Error: socket hang up
Warning: This request did not get sent completely and might not have all the required system headers
如果NodeJS服务器在nginx反向代理后面,则nginx返回502响应(upstream prematurely closed connection while reading response header from upstream
)。但是这里只是在本地主机上运行的NodeJS / express。还有人会期望适当的http响应。
根据this answer,这是预期的行为,套接字被简单破坏。
在具有nginx反向代理的体系结构中,通常服务器只是销毁套接字而不向代理发送超时响应吗?
回答如下:您正在设置socket timeout when you're setting the http server timeout。套接字超时可以防止来自可能希望挂接到您与DOS的连接的客户端的滥用。它还有其他好处,例如确保一定水平的服务(尽管当您是客户时,这些通常更重要)。
之所以使用套接字超时而不是发送408
状态代码(请求超时),是因为可能已经发送了成功消息的状态代码。
如果要在后端实现响应超时并妥善处理,则可以自己使响应超时。注意,您可能应该用408
代替。 502
用于诸如http代理(nginx)之类的网关,以指示下游连接失败。
这是处理该问题的简单稻草人实现。
const httpServer = require('http').createServer((req, res) => {
setTimeout(()=>{
res.statusCode = 200;
res.statusMessage = "Ok";
res.end("Done"); // I'm never called because the timeout will be called instead;
}, 10000)
});
httpServer.on('request', (req, res) => {
setTimeout(()=>{
res.statusCode = 408;
res.statusMessage = 'Request Timeout';
res.end();
}, 1000)
});
httpServer.listen(8080);
更多推荐
为什么NodeJS http服务器在超时时没有响应就关闭套接字?
发布评论