Elmseld
How do I make two Elixir applications(server & client) communicate with Phoenix.PubSub?
I have two elixir-applications, that need to communicate with each other:
- 1 Server that has a
PubSubwith 2topics, it broadcasts to onetopicand listens to the othertopic. - 1 Client, that should subscribe to the Servers
PubSubtopicandbroadcastto the othertopic.
The scenario I want to get is that I start the Server, and then start one or multiple Clients that can subscribe to the server.
It just needs to work locally in the terminal, so it doesn’t need any fancy.
The Server uses :phoenix_pubsub, "~> 2.1" and the rest is mostly a Genserver for message-handling.
The client is basically just a Genserver that only needs to subscribe to the server and sends A message when it receives one.
Any tips on how I can make them talk?
Marked As Solved
kokolegorille
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… ![]()
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







