跳至內文 跳至搜尋

Action Controller Live 伺服器發送事件

這個類別提供將 SSE (伺服器發送事件) 寫入 IO 串流的功能。類別初始化時需提供串流,可用於寫入 JSON 字串或可轉換為 JSON 的物件。

寫入物件會將它轉換為標準 SSE 格式,採用您設定的任何選項。您可以選擇設定下列選項

:event

若有指定,會在瀏覽器中發送具有此名稱的事件。

:retry

在嘗試發送事件時使用的重新連線時間 (毫秒)。

:id

如果在發送 SSE 到瀏覽器時連線中斷,伺服器將收到一個 Last-Event-ID 標頭,其值等於 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 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