How do I make two Elixir applications(server & client) communicate with Phoenix.PubSub?

Hello and welcome,

You could add pub_sub as a dependency in the client, then add it to the client supervision tree with the same name as the one in Phoenix.

You need to cluster both nodes. I use libcluster for this, but You have other options.

Then, it should work… :slight_smile:

For example

$ mix new demo --sup
$ cd demo
# add deps in mix.exs
# {:phoenix_pubsub, "~> 2.1"},
# start pub_sub in lib/demo/application.ex
# {Phoenix.PubSub, name: Demo.PubSub},
$ mix deps.get

Start first node and subscribe to pub_sub…

$ iex --sname demo1 --cookie cookie -S mix
iex(demo1@arakis)1> Phoenix.PubSub.subscribe(Demo.PubSub, "topic")
:ok

Start second node in another console, connect both nodes, and broadcast a message…

$ iex --sname demo2 --cookie cookie -S mix
iex(demo2@arakis)1> Node.ping :demo1@arakis
:pong
iex(demo2@arakis)2> Node.list
[:demo1@arakis]
iex(demo2@arakis)3> Phoenix.PubSub.broadcast(Demo.PubSub, "topic", %{message: "Hey there!"})
:ok

Receive message in first node…

iex(demo1@arakis)2> flush
%{message: "Hey there!"}
:ok
8 Likes