在后端订阅Phoenix Channel(不是channel.join())

时间:2017-07-27 03:49:06

标签: sockets websocket phoenix phoenix-channels

是否可以将套接字订阅到后端的某些Phoenix通道而不是客户端?假设我有一些用户所属的组,并且我希望用户在建立WS连接后连接到它们。向用户发送组ID以及加入频道似乎是不必要的往返,特别是我想在一个回调中处理该组中的消息,所以我在Socket上使用onMessage并通过掩码进行匹配。我该怎么做?

1 个答案:

答案 0 :(得分:0)

不确定这是否是一个好的解决方案,可能它使用了一些非私有的内部API:

  defmodule Front.UserChannel do
  use Front.Web, :channel

  def join("user:" <> user_id, _payload, socket) do
    if Integer.to_string(socket.assigns[:user_id]) == user_id do
      send(self(), :after_join)
      {:ok, socket}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end

  def handle_info(:after_join, socket) do
    Groups.associated_with(socket.assigns[:user_id])
    |> Enum.each(fn group_id ->
      %Phoenix.Socket{socket | topic: "group:#{group_id}", channel: Front.GroupChannel}
      |> Phoenix.Channel.Server.join(%{})
    end)
    {:noreply, socket}
  end
end
相关问题