跳至內容 跳至搜尋

Action Cable 伺服器 廣播

廣播 是應用程式其他部分可以用來傳送訊息給頻道的訂閱者。 如同在 頻道 所解釋的,這些廣播大部分都會直接串流給訂閱了該命名廣播的用戶端。讓我們用一個全堆疊範例來解釋

class WebNotificationsChannel < ApplicationCable::Channel
  def subscribed
    stream_from "web_notifications_#{current_user.id}"
  end
end

# Somewhere in your app this is called, perhaps from a NewCommentJob:
ActionCable.server.broadcast \
  "web_notifications_1", { title: "New things!", body: "All that's fit for print" }

# Client-side CoffeeScript, which assumes you've already requested the right to send web notifications:
App.cable.subscriptions.create "WebNotificationsChannel",
  received: (data) ->
    new Notification data['title'], body: data['body']
命名空間
方法
B

執行個體公開方法

broadcast(broadcasting, message, coder: ActiveSupport::JSON)

直接廣播一個雜湊到一個名為 broadcasting 的地方。此部分稍後會進行 JSON 編碼。

# File actioncable/lib/action_cable/server/broadcasting.rb, line 31
def broadcast(broadcasting, message, coder: ActiveSupport::JSON)
  broadcaster_for(broadcasting, coder: coder).broadcast(message)
end

broadcaster_for(broadcasting, coder: ActiveSupport::JSON)

傳回一個名為 broadcasting 的廣播放送器,可重複使用。當你有物件可能需要多個位置來傳輸到特定廣播時很有用。

# File actioncable/lib/action_cable/server/broadcasting.rb, line 38
def broadcaster_for(broadcasting, coder: ActiveSupport::JSON)
  Broadcaster.new(self, String(broadcasting), coder: coder)
end