为什么NodeJS http服务器在超时时没有响应就关闭套接字?

编程入门 行业动态 更新时间:2024-10-07 06:46:28

为什么NodeJS http<a href=https://www.elefans.com/category/jswz/34/1771423.html style=服务器在超时时没有响应就关闭套接字?"/>

为什么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服务器在超时时没有响应就关闭套接字?

本文发布于:2024-05-07 07:26:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1755134.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:服务器   NodeJS   http

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!