Establish a Client Connection
Let's understand how to write code for the client-side.
We'll cover the following...
Client-side code
Our goal in this section is to write a client code that can invoke the join/3
function we now have on the server. There are a few steps to make that happen:
-
We need to define a client socket and use it to establish a connection to the socket on the server. Then, we need to define a new Channel object on the client, and use it to join the Channel on the server.
-
Phoenix ships with
phoenix.js
—a JavaScript file that knows all about working with sockets and Channels. It’s indispensable for writing JavaScript client code for Channels, and our first task is to make it available in the browser’s console window.
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
Let’s go to Player 1’s JavaScript console and acquire the phoenix.js
file.
Note: Open the widget link in two separate browser tabs and open the developer tools. Run the following commands in the JavaScript console.
We need to instantiate a new socket object to establish a ...