如何Endpoint.broadcast到另一个频道的主题和事件?

时间:2017-12-09 05:55:11

标签: elixir phoenix-framework

我定义了两个频道。 第一个是

defmodule AppServerWeb.FirstChannel do
  use Phoenix.Channel

  def join("first:*", auth_key, socket) do
      send(self, {:after_join, 12})
      {:ok, socket}
  end

  def handle_info({:after_join, count}, socket) do
        App.Endpoint.broadcast "second:*", "activeusers", %{users: count}
        {:noreply, socket}
  end

  def handle_out(event, payload, socket) do
      push socket, event, payload
      {:noreply, socket}
  end

end

第二个是

defmodule AppServerWeb.SecondChannel do
  use Phoenix.Channel

  def join("second:*", auth_key, socket) do
      {:ok, socket}
  end


  def handle_out(event, payload, socket) do
      push socket, event, payload
      {:noreply, socket}
  end

end

在我的客户端,我有

socket = new Phoenix.Socket("/socket", {params: {userToken: "123"}})
socket.connect();
channel1 = socket.channel("first:*", {auth: "foo"})
channel2 = socket.channel("second:*", {auth: "foo"})
channel1.join()   //successful join
channel2.join()   //successful join
channel2.on("activeusers", function (msg) {
        console.log(msg)   //This one never triggers
});

所以基本上所有我需要的是从第一频道广播一个主题,并从加入到channel2的客户端收听它,这是我可以去阅读文档,这是行不通的..我在哪里搞砸了?

1 个答案:

答案 0 :(得分:0)

根据Phoenix.Channel上的文件:

  

在某些情况下,您需要在没有套接字上下文的情况下广播消息。这可以用于从您的频道内广播到外部主题,或者从应用程序的其他位置广播,如控制器或其他进程。这可以通过您的终端来完成:

# within channel
def handle_in("new_msg", %{"uid" => uid, "body" => body}, socket) do
  ...
  broadcast_from! socket, "new_msg", %{uid: uid, body: body}
  MyApp.Endpoint.broadcast_from! self(), "room:superadmin",
    "new_msg", %{uid: uid, body: body}
  {:noreply, socket}
end

也就是说,您应该使用broadcast_from!/4传递self()作为第一个参数。