Communication Between Players
Understand how both players communicate in Islands’ engine.
We'll cover the following...
Communication between the players
Now, let’s look at how push/3
works inside the GameChannel
. Instead of a reply tuple, this will send a new event down the Channel, but only to the original caller. Since we don’t rely on a reply tuple to communicate back to the client, we replace it with {:noreply, socket}
.
The path of message passing will look the same as the reply shown in the following figure.
Let’s go to the Channel and change the handle_in/3
clause to use push/3
. We could leave the :reply
tuple there and get two responses. However, since push/3
will already send a reply, it makes more sense to swap in {:noreply, socket}
instead:
Let’s compile the GameChannel
so we can see handle_in/3
in action:
def handle_in("hello", payload, socket) do
push socket, "said_hello", payload
{:noreply, socket}
end
New IEx session
Now, let’s head over to Player 1’s console and give it a try:
defmodule IslandsInterface.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do children = [ # Start the Telemetry supervisor IslandsInterfaceWeb.Telemetry, # Start the PubSub system {Phoenix.PubSub, name: IslandsInterface.PubSub}, # Start the Endpoint (http/https) IslandsInterfaceWeb.Endpoint # Start a worker by calling: IslandsInterface.Worker.start_link(arg) # {IslandsInterface.Worker, arg} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: IslandsInterface.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do IslandsInterfaceWeb.Endpoint.config_change(changed, removed) :ok end end
We need to do all the ...