在服务器端使用带有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 1024在upstream部分以及proxy_set_header Connection keep-alive;在 …
这是我为解决问题而设置的一个简单的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异常.
这是我到目前为止所尝试的:
搜索互联网也提供了很少的帮助.
我很茫然,需要一些指导.
这是两个curl调用的输出,有和没有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)