Phoenix Channels - Multiple channels per socket

前端 未结 3 1913
一个人的身影
一个人的身影 2020-12-21 00:26

I\'m writing an application using Elixir Channels to handle realtime events. I understand that there will be 1 socket open per client and can multiplex multiple channels ove

3条回答
  •  盖世英雄少女心
    2020-12-21 00:51

    Disclaimer: I have not looked at the internal workings of a channel, this information is completely from my first experience of using channels in an application.

    When someone joins a different group (based on the pattern matching in your join/3), a connection over a separate channel (socket) is made. Thus, broadcasting to A will not send messages to members of B, only A.

    It seems to me the Channel module is similar to a GenServer and the join is somewhat like start_link, where a new server (process) is spun up (however, only if it does not already exist).

    You can really ignore the inner workings of the module and just understand that if you join a channel with a different name than already existing ones, you are joining a unique channel. You can also just trust that if you broadcast to a channel, only members of that channel will get the message.

    For instance, in my application, I have a user channel that I want only a single user to be connected to. The join looks like def join("agent:" <> _agent, payload, socket) where agent is just an email address. When I broadcast a message to this channel, only the single agent receives the message. I also have an office channel that all agents join and I broadcast to it when I want all agents to receive the message.

    Hope this helps.

提交回复
热议问题