跳至内容 跳至搜索

Action Cable Server Broadcasting

Broadcasting 是应用程序的其他部分如何向通道的订阅者发送消息的方式。如 Channel 中所述,大多数情况下,这些广播直接流式传输到订阅了命名广播的客户端。让我们通过一个完整的堆栈示例来解释

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