AlejandroHuerta
Connecting to Channel from within application
Hey everyone, here’s my use case: I have a channel that sends events to a GenServer running a simulation and that GenServer responds, as well as sends broadcast back to the channel. Now I want to create another GenServer that can connect to that same channel and send and receive messages like any other client.
I’ve done some searching and noticed there are libraries that implement a full client, as in use websockets to connect to the channel, but that seems overkill since my new GenServers are running within the same application. Is there anyway to achieve this without running a full client?
Failing this I think I could just have the two GenServers communicate directly with each other but I would like to avoid creating a different communication channel within my simulation.
Marked As Solved
chrismccord
You can simply use PubSub. Subscribe to the channel topic to “listen in” on the channel messages. Broadcast on the channel topic to send messages to channel processes.
def init(...) do
MyApp.Endpoint.subscribe("room:123")
...
end
alias Phoenix.Socket.Broadcast
def handle_info(%Broadcast{topic: "new_msg"} = msg, state) do
# do something on new chat message broadcasted by channel process
end
def broadcast_new_msg(body) do
MyApp.Endpoint.broadcast_from(self(), "room:123", "new_msg", %{body: body})
end
Last Post!
westmark
Ok thank you for clarifying that. And “re-broadcasting” was just a poor choice of words, didn’t actually mean “broadcasting again”
I had solved it in a similar way, but with GenServer.call instead.
Popular in Questions
Other popular topics
Latest Phoenix Threads
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









