跳至内容 跳至搜索

Action Controller Live 服务器发送事件

此类提供将 SSE(服务器发送事件)写入 IO 流的能力。此类使用流进行初始化,可用于写入 JSON 字符串或可转换为 JSON 的对象。

写入对象会将该对象转换为标准的 SSE 格式,并应用您配置的所有选项。您可以选择设置以下选项:

:event

如果指定,则会在浏览器上触发具有此名称的事件。

:retry

尝试发送事件时用于重新连接的时间(以毫秒为单位)。

:id

如果连接在向浏览器发送 SSE 时断开,则服务器将收到一个值为 idLast-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 都支持它。

方法
C
N
W

常量

PERMITTED_OPTIONS = %w( retry event id )
 

类公共方法

new(stream, options = {})

# File actionpack/lib/action_controller/metal/live.rb, line 115
def initialize(stream, options = {})
  @stream = stream
  @options = options
end

实例公共方法

close()

# File actionpack/lib/action_controller/metal/live.rb, line 120
def close
  @stream.close
end

write(object, options = {})

# 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