使用 Sinatra 和 stream
块在服务器端实现。
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/
访问时,一切都很完美。连接是持久的,所有消息都传递给了所有客户端。
但是当它通过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;
}
}
尝试在upstream
部分添加keepalive 1024
,并在location
中添加proxy_set_header Connection keep-alive;
但这些都没有起作用 :(
没有持久连接,并且消息未传递给任何客户端。
proxy_buffering off; proxy_cache off;
- Malcolm Sparks