Ruby on rails Rails写入已打开的实时SSE流
在rails中,您可以在控制器中创建SSEServer发送的事件流,如下所示:Ruby on rails Rails写入已打开的实时SSE流,ruby-on-rails,ruby,Ruby On Rails,Ruby,在rails中,您可以在控制器中创建SSEServer发送的事件流,如下所示: class MyController < ActionController::Base include ActionController::Live def index response.headers['Content-Type'] = 'text/event-stream' sse = SSE.new(response.stream, retry: 300, event: "eve
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中的示例。在我看到的所有rails示例中,它们都使用了基于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
谢谢你的帮助