事件源/服务器通过 Nginx 发送的事件 [英] EventSource / Server-Sent Events through Nginx

查看:48
本文介绍了事件源/服务器通过 Nginx 发送的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在服务器端使用带有 stream 块的 Sinatra.

On server-side using Sinatra with a stream block.

get '/stream', :provides => 'text/event-stream' do
  stream :keep_open do |out|
    connections << out
    out.callback { connections.delete(out) }
  end
end

在客户端:

var es = new EventSource('/stream');
es.onmessage = function(e) { $('#chat').append(e.data + "
") };

当我通过 http://localhost:9292/ 直接使用应用程序时,一切正常.连接是持久的,所有消息都传递给所有客户端.

When i using app directly, via http://localhost:9292/, everything works perfect. The connection is persistent and all messages are passed to all clients.

然而,当它通过 Nginx 时,http://chat.dev,连接被断开并且每隔一秒左右就会重新连接一次.

However when it goes through Nginx, http://chat.dev, the connection are dropped and a reconnection fires every second or so.

Nginx 设置对我来说还不错:

Nginx setup looks ok to me:

upstream chat_dev_upstream {
  server 127.0.0.1:9292;
}

server {
  listen       80;
  server_name  chat.dev;

  location / {
    proxy_pass http://chat_dev_upstream;
    proxy_buffering off;
    proxy_cache off;
    proxy_set_header Host $host;
  }
}

upstream 部分以及 proxy_set_header Connection keep-alive;location 中尝试了 keepalive 1024.

Tried keepalive 1024 in upstream section as well as proxy_set_header Connection keep-alive;in location.

没有任何帮助:(

没有持久连接和消息不会传递给任何客户端.

No persistent connections and messages not passed to any clients.

推荐答案

你的 Nginx 配置是正确的,你只是错过了几行.

Your Nginx config is correct, you just miss few lines.

这是一个神奇的三重奏",让 EventSource 通过 Nginx 工作:

Here is a "magic trio" making EventSource working through Nginx:

proxy_set_header Connection '';
proxy_http_version 1.1;
chunked_transfer_encoding off;

将它们放入 location 部分,它应该可以工作.

Place them into location section and it should work.

您可能还需要添加

proxy_buffering off;
proxy_cache off;

这不是官方的做法.

我通过反复试验"+谷歌搜索"来解决这个问题:)

I ended up with this by "trial and errors" + "googling" :)

这篇关于事件源/服务器通过 Nginx 发送的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆