I wanted to write a multinode elixir example for multiple people on the same network. A toy direct messaging app that can be run from iex is created in this post. Any number of people can participate, but this post is largely written as if there are only two participants.
Software Versions
Instructions
First, start a new project and create a directory for the messenger module.
Next, we need some code to run on the nodes. Add the following to lib/multiplayer/messenger.ex.
Nodes have a name in the form :name@host. The node_name function discards the @host portion and returns :name. This :name atom is passed to :global.register_name so any node on the network can look up any other messenger without having to know the host or IP address. This is not a production ready solution, but it is good enough for this example.
The message function can send a message by messenger pid or node :name. The uppercase node name is prepended to the message on the sending node. IO.puts runs in the receiving node and prints the message in iex. Messages are send and forget, so handle_cast is used. This GenServer has no state.
Next, set up supervision in lib/multiplayer.ex.
Start the project in iex on two different machines on the same network. Make sure the node names are different. Also, make sure to append a routable host or IP address to the node name.
Connect one of the nodes to the other. This will connect both nodes to one another. If there are more than two nodes, the remaining nodes can connect to any of the already connected nodes. Each node only needs to connect once.
Send messages back and forth by calling Multiplayer.Messenger.message :name, “message”
Messages are not broadcast to all participants. Each message is only sent to the specified party. Output will look something like this.