Receive Messages

Receiving messages from a client

Receiving requests from a client and sending a response is critical to all applications. This lets our users interact with our real-time application without writing additional entry points, such as controller actions. For example, when a client sends a message over the WebSocket connection that powers their Channels, we can also avoid creating traditional HTTP controller code. We’ll see how to handle a client’s request and send various response types.

When a client sends a message to a Channel, the transport process receives it and delegates it to the Socket’s handle_in/2 callback. The Socket sends the decoded message struct to the correct Channel process and handles errors such as a mismatched topic—the Phoenix.Channel. The server process handles the sent message by delegating to the associated Channel implementation’s handle_in/3 callback. This happens transparently to us, meaning that we only need to be concerned with the client sending a message and our Channel’s handle_in/3 callback processing the message.

A benefit of this heavily process-based flow is that the Socket will not block while waiting for the Channel to process the message. This allows us to have many Channels on a single Socket while still maintaining the high performance of our system.

Using pattern matching to craft powerful functions

Let’s look at a few examples of writing our handle_in/3 function to use pattern matching and different return values. We’ll modify our PingChannel to respond differently to a ping message if the payload contains specific values. Place this code above the existing handle_in/3 function.

Get hands-on with 1200+ tech skills courses.