Building a Plain Talk App With Elixir and Phoenix – Sheharyar Naseer

Без кейворда

The past few years, more and more applications have been transitioning to websockets for real-time communication, even forcing some frameworks to implement them (such as ActionCable in Rails Five). The Phoenix Framework for Elixir implements it natively, without depending on any outer programs such as Redis .

Today, we’re going to build a super plain talk application in Elixir using the Phoenix Framework. We’re going to disregard authentication, authorization and other features so we can quickly go over the basics, and get websockets in Elixir running.

Getting Embarked

Embark by installing Elixir and Phoenix. Optionally, check out my talk on Introduction to Elixir. Create a fresh phoenix project and call it whatever you like, and commence the server so you can see the app in your browser:

Creating the View

Let’s begin with something effortless by writing the markup and CSS for our talk app. Open web/templates/page/index.html.eex , and substitute its contents with:

We’ve created an empty div that will list all talk messages and two text fields (one for the user’s name and one for the message). Now open web/static/css/app.css and paste this at the end:

Point your browser to localhost:4000 , it should look like this:

Setting up a fresh Channel

We’re going to create a fresh channel called lobby . Open up web/channels/user_socket.ex and add this line:

Create a fresh file called web/channels/lobby_channel.ex and implement the functionality for the fresh lobby channel. The join method here always comebacks <:ok, socket>to permit all connections to the channel. The handle_in method is fired every time a fresh incoming message is received on the socket, which broadcasts that message to all other open sockets.

Treating the connections on Client-side

To make things lighter, we’ll commence by adding jQuery to our web/templates/layouts/app.html.eex :

Phoenix comes packed with a elementary javascript socket client, but it’s disabled by default. Go into your web/static/js/app.js and uncomment the last line:

Go into your web/static/js/socket.js and paste in this:

Here, we listen for a keypress event on the message text field. Whenever the user comes in a message, it’s shoved on the channel and the text field is cleared. When there’s an incoming message on the channel, it’s appended to the div we previously created and scrolled to the bottom.

Going from there

So far we’ve implemented a super plain talk application in Elixir. It’s obviously not flawless and there’s alot of stuff missing. The next logical step would be to add some sort of authentication and authorization, and implement more one-on-one and private talk rooms.

Related video:

Leave a Reply

Your email address will not be published. Required fields are marked *