Customize Channel Behavior
A Phoenix Channel is backed by a GenServer that lets it receive messages and store state. We can take advantage of this property of Channels to customize the behavior of our Channel on a per-connection level. This allows us to build impossible flows (or flows that would be much more complex) with standard message broadcasting, which can’t easily send messages to a single client.
We can’t customize the behavior
of Sockets as much due to their process structure. We’ll focus our attention strictly on Channel-level customization for these examples by walking through several different patterns that use
Phoenix.Socket.assign/3 and message sending.
Send a recurring message
We sometimes need to send data to a client in a systematic way. One use case is to refresh an authentication token every few minutes to ensure that a client always has a valid token. This is useful because it is possible to overwhelm a server if all clients ask for a token simultaneously.
Our Channel will send itself a message every five seconds using
Process.send_after/3. This flow will be started when the Channel process initializes, but it would be possible to start the flow in our
handle_in callback in response to a client-initiated message.
First, add a new
recurring Channel route to the