跳至内容 跳至搜索

Action Controller 实时服务器发送事件

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

写入对象会将其转换为标准 SSE 格式,其中包含您配置的任何选项。您可以选择设置以下选项

1) Event. If specified, an event with this name will be dispatched on
the browser.
2) Retry. The reconnection time in milliseconds used when attempting
to send the event.
3) Id. If the connection dies while sending an SSE to the browser, then
the server will receive a +Last-Event-ID+ header with value equal to +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

注意:IE 目前不支持 SSE。但是,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 110
def initialize(stream, options = {})
  @stream = stream
  @options = options
end

实例公共方法

close()

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

write(object, options = {})

# File actionpack/lib/action_controller/metal/live.rb, line 119
def write(object, options = {})
  case object
  when String
    perform_write(object, options)
  else
    perform_write(ActiveSupport::JSON.encode(object), options)
  end
end