Implementation of a Channel
Channels are the real-time entry points to our application’s logic and where most applications’ request handling code lives. A Channel has several different responsibilities to enable real-time applications:
- Accept or reject a request to join.
- Handle messages from the client.
- Handle messages from the PubSub.
- Push messages to the client.
Channels,Controllers, and Sockets
The distinction between Channels and Sockets may not be evident at a glance. A Socket’s responsibilities involve connection handling and routing requests to the correct Channel. A Channel’s responsibilities include handling requests from a client and sending data to a client. In this way, a Channel is similar to a Controller in the MVC (Model-View-Controller) design pattern.
In recent years, it has become popular to use the mantra “skinny controllers” to indicate that we don’t want business logic in our controllers. This same mantra can be applied to Channels; we should strive to keep application logic in our application’s core and not implement it in our Channels. The exception is that logic needed for real-time communication customization is best implemented at the Channel level, as we’ll see in Customize Channel Behavior, in the coming lesson.
Implement our first Channel
Let’s implement our
PingChannel. This implementation won’t have any application logic and is fully self-contained. Let’s create a new file under the
channels directory and name it as