concept channel in category elixir

appears as: chnels, chnel, channel, chnel
Phoenix in Action

This is an excerpt from Manning's book Phoenix in Action.

Elixir can spawn and efficiently handle hundreds of thousands of processes without blinking an eye (we’ll go into a bit more detail later in this chapter). When creating channels for real-time communication, Phoenix spawns each channel in its own process, so that no single process can damage or take down any of the others—they’re isolated.

Using these processes and channels, Phoenix can handle hundreds of thousands of connections on a single server. Kudos to you if your web application ever has hundreds of thousands of simultaneous users wanting to communicate in real time, but that gives you an idea of the power of Phoenix and channels running within processes.

You’ll add channels in the application you’ll build over the course of this book.

Behind the scenes, Phoenix channels make use of Elixir processes. We discussed Elixir processes in chapter 1, but the main thing you need to know is that they’re very lightweight—they take up minimal server resources, and they allow Elixir modules to pass messages back and forth and maintain state. Without getting too much into the technical details, Phoenix uses those Elixir processes and a pubsub (publish-subscribe) mechanism to allow different clients to subscribe to different “topics” and “subtopics.” One of the great consequences of Elixir processes being so lightweight (and channels being implemented on top of them) is that a huge number of simultaneous connections can be handled—it’s been tested with millions of clients being connected to moderate server hardware.

For your Auction application, when a user visits an auction item’s page, the user will be subscribed to a topic of “item” and a subtopic of the item’s ID (for example, "item:123"). You can then broadcast messages on that topic/subtopic combo, and the user’s client will receive that message. You can then write some simple JavaScript to respond to that message. For this implementation, the response will be to update the list of bids in the user’s browser with the information passed along in the broadcasted message. On the other side of the channel, whenever a user submits a new bid for an item, you’ll accept that bid and broadcast it to all the clients connected to that item’s topic/subtopic.

Now that you’ve imported the Socket class, you need to instantiate a new instance of the class with the parameters you require. By default, channels communicate over the /socket path of your app (you can customize this in AuctionWeb.Endpoint), so you’ll tell it that that’s the path you’d like to connect over. Furthermore, you pass a userToken as a param. You could use that param for user authentication if you needed or wanted authentication. This is all code that’s generated by Phoenix’s Mix task; you won’t need a userToken in your implementation.