Basic Websocket Chat Example Using the Cowboy Server w/o Phoenix

websockets
#1

Here is an example of a Mix application that utilizes Cowboy to handle websocket connections. If anyone has an idea about making this work with multiple nodes that would be helpful for the question posed in the comments. Thanks.

1 Like

#2

:wave:

Instead of

file = EEx.eval_file("lib/application.html.eex")

you might want to compile the template to a function

require EEx
EEx.function_from_file(:defp, :index_html, "lib/application.html.eex", [])

get "/" do
  send_resp(conn, :ok, index_html())
end

it would help you avoid reevaluating the template on each request.


For distribution, there are several options worth exploring, you can go the “phoenix route” and make a basic pubsub or you can go “riak route” and use a hash ring to distribute chat processes across nodes. The former is simpler, the latter is less chatty.

5 Likes

#3

Thanks for the tip of function_from_file. I will update the post using it.

As far as distribution goes I found a comment from a post that said Phoenix uses the :pg2 module from Erlang. I quickly checked it out and found that you can easily setup a distributed PubSub with it!

Somewhere in your app you would need to register a group :pg2.create("Global")

Then, in my case, I would add pids to this group with :pg2.join("Global", self()), then when sending messages to these pids you would get them all with :pg2.get_members("Global") which grabs all pids from all the connected nodes, and finally send them a message with something like Process.send\3

The Elixir and Erlang ecosystem makes it so easy sometimes :smile:

0 Likes