Action Controller Live 服务器发送事件¶ ↑
此类提供将 SSE(服务器发送事件)写入 IO 流的能力。此类使用流进行初始化,可用于写入 JSON 字符串或可转换为 JSON 的对象。
写入对象会将该对象转换为标准的 SSE 格式,并应用您配置的所有选项。您可以选择设置以下选项:
:event-
如果指定,则会在浏览器上触发具有此名称的事件。
:retry-
尝试发送事件时用于重新连接的时间(以毫秒为单位)。
:id-
如果连接在向浏览器发送
SSE时断开,则服务器将收到一个值为id的Last-Event-ID标头。
在 SSE 对象的构造函数中设置选项后,流上发送的所有未来 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
注意:SSE 目前不受 IE 支持。但是,Chrome、Firefox、Opera 和 Safari 都支持它。
方法
常量
| PERMITTED_OPTIONS | = | %w( retry event id ) |
类公共方法
new(stream, options = {}) 链接
来源: 显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/live.rb, line 115 def initialize(stream, options = {}) @stream = stream @options = options end
实例公共方法
close() 链接
来源: 显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/live.rb, line 120 def close @stream.close end
write(object, options = {}) 链接
来源: 显示 | 在 GitHub 上
# File actionpack/lib/action_controller/metal/live.rb, line 124 def write(object, options = {}) case object when String perform_write(object, options) else perform_write(ActiveSupport::JSON.encode(object), options) end end