使用 Rails 4 实现服务器发送事件

Implement Server Send Events with Rails 4

我正在尝试在乘客 Rails 4 运行 中实施服务器发送事件。目的是在活动记录更改时向客户端发送更新。

这里 php 中有一个非常简洁的示例

但我想知道在 rails 中这是如何实现的。 rails 是否需要任何特定配置来管理连接?

在这里找到了解决方案: http://api.rubyonrails.org/classes/ActionController/Live.html

只包含活动控制器,并编写一个简单的动作:

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

  def stream
    response.headers['Content-Type'] = 'text/event-stream'
    100.times {
      response.stream.write "hello world\n"
      sleep 1
    }
  ensure
    response.stream.close
  end
end