相关疑难解决方法(0)

通过Nginx发送EventSource/Server-Sent事件

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

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

在客户端:

var es = new EventSource('/stream');
es.onmessage = function(e) { $('#chat').append(e.data + "\n") };
Run Code Online (Sandbox Code Playgroud)

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

但是当它通过Nginx时http://chat.dev,连接被丢弃并且重新连接每隔一秒左右触发一次.

Nginx设置对我来说没问题:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

尝试keepalive 1024upstream部分以及proxy_set_header Connection keep-alive;在 …

ruby nginx sinatra

66
推荐指数
4
解决办法
2万
查看次数

Rails 4,Puma,Nginx - ActionController :: Live Streaming在第一个块发送后死亡

这是我为解决问题而设置的一个简单的Rails 4项目:

https://github.com/rejacobson/rails4-streamtest

我在/ home/stream设置了一个路由,它应该以1秒的间隔流式传输一行文本5次.

def stream
  5.times do |n|
    puts "Streaming: #{n}"
    response.stream.write "Streaming: #{n+1}"
    sleep 1
  end
rescue IOError => e
  puts 'Connection closed'
ensure
  response.stream.close
end
Run Code Online (Sandbox Code Playgroud)

当我使用tcp://运行puma,没有nginx时,流式传输完美无缺.

curl -N http://localhost:3000/home/stream
Run Code Online (Sandbox Code Playgroud)

我得到5行流回来,没问题.

当我引入nginx时,curl将输出第一行但在此之后立即退出.我继续看到来自服务器和日志的puts调用的输出,所以我知道请求仍在5.times循环中处理.

它也不会像用户切断连接时那样抛出IOError异常.

这是我到目前为止所尝试的:

  • 主conf文件和服务器conf中的nginx指令的不同组合.
  • 更改导轨设置.
  • 各种puma配置设置.
  • 在控制器方法中设置各种不同的标头,希望它是一个缓存问题.

搜索互联网也提供了很少的帮助.

我很茫然,需要一些指导.

这是两个curl调用的输出,有和没有nginx.

没有nginx

~/projects/streamtest ? master ?
ryan mirage ???? curl -i -N http://192.168.1.100:3000/home/stream
HTTP/1.1 200 OK
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-UA-Compatible: chrome=1
Cache-Control: no-cache
Content-Type: text/html; charset=utf-8
Set-Cookie: request_method=GET; path=/
X-Request-Id: 9ce86358-4476-404a-97e5-769c16ec7b0c
X-Runtime: 0.978099 …
Run Code Online (Sandbox Code Playgroud)

streaming ruby-on-rails nginx puma ruby-on-rails-4

10
推荐指数
1
解决办法
3048
查看次数

标签 统计

nginx ×2

puma ×1

ruby ×1

ruby-on-rails ×1

ruby-on-rails-4 ×1

sinatra ×1

streaming ×1