ericlathrop

ericlathrop

Broadcasting to Phoenix Channel without Phoenix?

I’ve got an umbrella app with a Phoenix app, and some vanilla elixir apps. Is there a way to broadcast to a Phoenix channel from a vanilla elixir app? I’d like to avoid adding a dependency on the Phoenix app to reference its Endpoint.

I’m working on using Phoenix.PubSub to do this, but I’m not having any luck. This code:

    Phoenix.PubSub.broadcast(Www.PubSub, topic, %{
      __struct__: Phoenix.Socket.Broadcast,
      topic: topic,
      event: event,
      payload: payload
    })

Is giving me this error:

[error] GenServer #PID<0.952.0> terminating
** (UndefinedFunctionError) function Www.TimeChannel.handle_out/3 is undefined or private. Did you mean one of:

      * handle_in/3
      * handle_info/2

    (www) Www.TimeChannel.handle_out("now", %{now: "yolo"}, %Phoenix.Socket{assigns: %{user_id: 14904}, channel: Www.TimeChannel, channel_pid: #PID<0.952.0>, endpoint: Www.Endpoint, handler: Www.UserSocket, id: "users_socket:14904", joined: true, pubsub_server: Www.PubSub, ref: nil, serializer: Phoenix.Transports.WebSocketSerializer, topic: "time:now", transport: Phoenix.Transports.WebSocket, transport_name: :websocket, transport_pid: #PID<0.909.0>})
    (phoenix) lib/phoenix/channel/server.ex:234: Phoenix.Channel.Server.handle_info/2
    (stdlib) gen_server.erl:601: :gen_server.try_dispatch/4
    (stdlib) gen_server.erl:667: :gen_server.handle_msg/5
    (stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Last message: %Phoenix.Socket.Broadcast{event: "now", payload: %{now: "yolo"}, topic: "time:now"}
State: %Phoenix.Socket{assigns: %{user_id: 14904}, channel: Www.TimeChannel, channel_pid: #PID<0.952.0>, endpoint: Www.Endpoint, handler: Www.UserSocket, id: "users_socket:14904", joined: true, pubsub_server: Www.PubSub, ref: nil, serializer: Phoenix.Transports.WebSocketSerializer, topic: "time:now", transport: Phoenix.Transports.WebSocket, transport_name: :websocket, transport_pid: #PID<0.909.0>}

I’m confused about it wanting to use handle_out because I’m not using intercept anywhere, but maybe I just have my message format wrong. I was hoping to get the vanilla elixir app to broadcast directly to the web browser clients.

Most Liked

chrismccord

chrismccord

Creator of Phoenix

handle_out is being called because It’s not respecting the channel subscriber fastlanining, but without seeing your code it’s hard to say why that is. In any case, instead of trying to build cheat by building the Phoenix.Socket.Broadcast, I would have the external app broadcast “raw” messages over pubsub that your phoenix app subscribes to. You could have the channel subscribe to the topic and forward the message in handle_info, or you can have server(s) in your app subscribing to external topics/events, and then relaying them to channels via MyApp.Endpoint.broadcast. This way you aren’t coupling the external app to your channel layer directly. This also gives you a place to do any necessary data munging from the external data to the client representation.

ericlathrop

ericlathrop

I did get it to work by making these changes:

  1. I removed the struct definition so my broadcast code looks like:
  defp broadcast(topic, event, payload) do
    Phoenix.PubSub.broadcast(Www.PubSub, topic, %{
      topic: topic,
      event: event,
      payload: payload
    })
  end

and I call it like:

broadcast("session:12345", "yolo", %{ yoloed: 1 })
  1. I added a handle_info into my SessionChannel:
  def handle_info(%{topic: _, event: ev, payload: payload}, socket) do
    push socket, ev, payload
    {:noreply, socket}
  end

I found that code at the bottom of the Channel docs under “Subscribing to external topics”.

It works, but seems a little fragile. I like @chrismccord’s idea of making a server (GenServer?) that uses Phoenix.PubSub to listen to my own format message, and then MyApp.Endpoint.broadcast them. How do I prevent double-broadcasts when I have 2 webservers running each with their own GenServer doing the message forwarding?

dorian-marchal

dorian-marchal

Same question, I have a channel that broadcast events (from handle_in), with:

broadcast!(socket, "update", state)

This works well until I subscribe to a PubSub in the join callback:

:ok = Phoenix.PubSub.subscribe(MyAppWeb.PubSub, "topic")

Since I have added this subscription, the events broadcast trigger errors:

** (UndefinedFunctionError) function MyAppWeb.GridChannel.handle_out/3 is undefined or private

I can add the missing handle_out/3 callback but this doesn’t feel right and I don’t understand why I should add it.

What am I missing?

EDIT: I found out why: I was using the same topic name for my channel and my PubSub subscription. I didn’t realize channels and “global” PubSub shared the same namespace for topics.

Where Next?

Popular in Questions Top

New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3271 126479 1222
New

We're in Beta

About us Mission Statement