Rails写入已经打开的实时SSE流

时间:2014-04-16 22:20:44

标签: ruby-on-rails ruby

在rails中,您可以在控制器中创建这样的SSE(服务器发送事件)流:

class MyController < ActionController::Base
  include ActionController::Live

  def index
    response.headers['Content-Type'] = 'text/event-stream'
    sse = SSE.new(response.stream, retry: 300, event: "event-name")
    sse.write({ name: 'John'})
    sse.write({ name: 'John'}, id: 10)
    sse.write({ name: 'John'}, id: 10, event: "other-event")
    sse.write({ name: 'John'}, id: 10, event: "other-event", retry: 500)
  ensure
    sse.close
  end
end

我想做的是从另一条路线写入此流,例如下面的sinatra中的此示例。在我见过的所有轨道示例中,他们使用基于redis的队列,这对于像这样的事情来说似乎有些过分,并且很容易在Sinatra中完成。

我想做的一个例子就是使用Sinatra而不是Rails:

get '/connect', provides: 'text/event-stream' do
    stream :keep_open do |out|
      connections << out

      #out.callback on stream close evt. 
      out.callback {
        #delete the connection 
        connections.delete(out)
      }
    end
  end

 post '/push' do
    connections.each { |out| out << "data: hi!"}
  end

感谢您的帮助!

0 个答案:

没有答案