Channel Clients
Look at the details of the Channel clients and JavaScript clients.
We'll cover the following
Any networked device can be used to connect to Channels. Languages with a WebSocket or HTTP client (for long polling) are easiest to get started with. There are official and unofficial clients that work out-of-the-box with Channels, and these clients can certainly make the task easier for us. A list of client libraries is maintained in the Phoenix Channel documentation. It’s a good idea to look at this list if we are getting started with a language other than a JavaScript project since writing a client from scratch is a decently large endeavor.
We’ll be looking at the official Phoenix Channel client in this lesson. We’ll use JavaScript in our browsers to interact with our Channels. We’ll be able to send and receive messages from the server while handling different errors that may occur. We’ll see how the JavaScript client reacts when it disconnects to ensure our applications are always available to users.
Official JavaScript client
The official client, worked on by the Phoenix core team, is written in JavaScript. This can be used for web applications, web extensions, React Native applications, or any JavaScript interpreter that supports WebSocket or long polling. We’ll be using this client for a significant project later in the course.
Any Channel client has a few key responsibilities that should be followed for all behavior to work as expected:
- Connect to the server and maintain the connection by using a heartbeat.
- Join the requested topics.
- Push messages to a topic and optionally handle responses.
- Receive messages from a topic.
- Handle disconnection and other errors gracefully and try to maintain a connection whenever possible.
We’ll cover how the JavaScript client satisfies each of these responsibilities. The JavaScript client has a clean API which will feel very familiar if we have used promise-based libraries. We will cover a small but critical part of the client API in this lesson—covering the whole library would not be beneficial. We can read the official documentation to see all available functions and options.
Sending messages with the JavaScript client
Let’s connect to the PingChannel
that we built earlier in the chapter. We’ll push a ping
event and receive a reply from the server, which we will process on the web page.
Get hands-on with 1400+ tech skills courses.