The Channel

A Phoenix channel is a conversation. The channel sends messages, receives messages, and keeps state. We call the messages events, and we put the state in a struct called socket.

A Phoenix conversation is about a topic, and it maps onto application concepts like a chat room, a local map, a game, or in our case, the annotations on a video. More than one user might be interested in the same topic at the same time. Channels give you tools to organize your code and the communication among users. The concept that makes channels so powerful in Elixir is that each user’s conversation on a topic has its own isolated, dedicated process.

Here’s the kicker. Whereas request/response interactions are stateless, conversations in a long-running process can be stateful. This means that for more-sophisticated user interactions like interactive pages or multiplayer games, you don’t have to work so hard to keep track of the conversation by using cookies, databases, or the like. Each call to a channel simply picks up where the last one left off.

This approach only works if your foundation guarantees true isolation and concurrency. True isolation means that one crashing process won’t impact other subscribed users. True concurrency means lightweight abstractions that won’t bleed into one another. Your channels will scale in the dimensions that are most important to you, including code complexity, performance, and manageability.

You may be thinking that channels can’t be this simple, but they are. Your channels application will have to worry about three things, each on both the client and the server:

  • Making and breaking connections
  • Sending messages
  • Receiving messages

In this chapter, you’ll learn each of those basic building blocks in greater detail. We’re primarily going to be building the interactive portion of our application. We’ll allow users to build annotations in real time, and rumbl will play back all video annotations for a user. We’ll do this in two parts. First, on the client side, we need to build some client code to make a connection, send messages, and receive messages. We’ll write our code in ES6, the latest generation of JavaScript. Then, on the server side, we’ll do the same. We’ll establish a connection and then write channels code to process each request in the conversation.

When we’re done, we’ll take advantage of some Phoenix infrastructure called Channel Presence. We’ll write a little bit of code so users of Rumbl will be able to tell exactly who’s logged in.

There’s plenty to do, so let’s get started.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.45.5