简体   繁体   English

Node.js上的Server-Sent Events连接超时通过Nginx

[英]Server-Sent Events connection timeout on Node.js via Nginx

I have a Node.js via Nginx setup and it involves Server-Sent Events. 我通过Nginx设置有一个Node.js,它涉及Server-Sent Events。

No matter what Nginx configuration I have, connection of sse is broken after 60 seconds and reinitialized again. 无论我有什么Nginx配置,sse的连接在60秒后被破坏并再次重新初始化。 It doesn't happen if I connect to application directly on port on which node serves it, so it's clearly some Nginx proxy issue. 如果我直接在哪个节点上为其提供服务的端口上连接应用程序,就不会发生这种情况,因此显然是一些Nginx代理问题。

I'd like to have no timeout on sse connection. 我想在sse连接上没有超时。 Is that possible? 那可能吗? I've tried tweaking send_timeout , keepalive_timeout , client_body_timeout and client_header_timeout but it doesn't change anything. 我试着调整send_timeoutkeepalive_timeoutclient_body_timeoutclient_header_timeout但它不会改变任何东西。 Below is my Nginx configuration. 下面是我的Nginx配置。

upstream foobar.org {
   server 127.0.0.1:3201;
}

server {
  listen 0.0.0.0:80;
  server_name   example.org;

  client_max_body_size 0;
  send_timeout 600s;

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;

    proxy_pass http://example.org/;
    proxy_redirect off;

    proxy_set_header Connection '';
    proxy_http_version 1.1;
    chunked_transfer_encoding off;
    proxy_buffering off;
    proxy_cache off;
  }
}

Answering to myself. 回答自己。 Actually solution was not that difficult to find, it just demanded careful look into nginx documentation. 实际上解决方案并不难找到,它只是需要仔细研究nginx文档。

proxy_read_timeout is a directive responsible for that, and by default it's set to 60 seconds. proxy_read_timeout是一个负责该操作的指令,默认设置为60秒。 So it can be easily fixed by setting eg: 所以可以通过设置例如:

proxy_read_timeout 24h;

Setting 0 won't work, it will actually make all your connections broken, therefore we need to come up with long enough timeout. 设置0将不起作用,它实际上会使所有连接断开,因此我们需要提供足够长的超时。

After fixing that I approached also the other issue, but this time related to how browsers handle the connection. 在修复之后我也接近了另一个问题,但这次与浏览器如何处理连接有关。 For some reason after 5 minutes of inactivity browsers silently discard the connection. 由于某些原因,在5分钟不活动后,浏览器会以静默方式丢弃连接。 What's worse neither side is informed that it's discarded, for both it still appears as if connection is online, but data doesn't get through. 更糟糕的是,没有任何一方被告知它被丢弃,因为它仍然看起来好像连接在线,但数据无法通过。 Fix for that is to send some keep alive ping on interval basis (plain sse comment works great). 修复这个问题是在间隔的基础上发送一些保持活动的ping(普通sse评论工作得很好)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM