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

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

问题描述

在服务器端使用带有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 + "\n") };

当我通过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的EventSource/服务器发送的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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