Search⌘ K
AI Features

Connecting Our First WebSocket

Explore how to create and connect your first WebSocket in Phoenix. This lesson guides you through setting up a project, installing dependencies, and running the Phoenix server, enabling you to build foundational real-time application components.

Create a WebSocket connection

To get up and running quickly, we’re going to leverage Phoenix’s initial project scaffold. This course will let us write and run code on the go, but if we want to follow along locally, this is a good time to go to the Appendix lesson in order to make sure that Elixir and Phoenix are set up properly on our system.

We’ll use mix phx.new to create our first example. We’ll be prompted to fetch and install dependencies during this process. Enter Y in order for the project to be started without manual steps.

Shell
mix phx.new hello_sockets --no-ecto
* creating hello_sockets/config/config.exs
...
Fetch and install dependencies? [Yn] Y

Run mix phx.server in the hello_sockets folder to start the server. If we get an error when starting the server, we should double-check that we are in the right folder and do not already have a program running on port 4000.

Once started, we’ll see the program running on port 4000:

Shell
mix phx.server
...
Compiling 12 files (.ex)
Generated hello_sockets app
[info] Running HelloSocketsWeb.Endpoint with cowboy 2.6.3 at 0.0.0.0:4000 [info]
Access HelloSocketsWeb.Endpoint at http://localhost:4000
Webpack is watching the files
...

Steps to create hello_sockets application

  1. Connect to the terminal by clicking on the below screen.

  2. Run the following command in the terminal given below and compare the results with the above code snippet labeled “Creating new phoenix project.”

Shell
mix phx.new hello_sockets --no-ecto
  1. Enter Y to fetch and install dependencies during this process and wait for the dependencies to be installed completely.

  2. Go to the hello_sockets directory by entering:

Shell
cd hello_sockets
  1. Run the Phoenix server by entering the following command and verify the result from the above-given code snippet with the caption “Running phoenix server”.
Shell
mix phx.server
Terminal 1
Terminal
Loading...