Converse Over a Channel

Learn how to define separate handle_in events for each game.

Bidirectional communications

This is where things start to get interesting. So far, we’ve sent a join message and gotten an ok back. However, Channels support much richer forms of bidirectional communications between clients and the server. We now take a closer look at the most common bidirectional communications. These will help us while building our own applications.

The simplest way to send a message back from the server is to return a :reply tuple from the Channel callback. This is a three-element tuple {:reply, some_response, socket}, where the middle element gets sent back to the client who originally sent the message. This should look really familiar after our work with GenServer.

Another way to talk back from a Channel is with the push/3 function. push/3 sends the caller back a string that represents a new event along with a data payload. The caller needs to listen for that event, and we can define whatever actions to take in response to it.

Broadcasting is another way for the server to send messages back to clients. The **broadcast/3** and broadcast!/3 functions also send a string that represents a new event, along with a payload. However, they send this event to every client that has subscribed to that specific topic subtopic.

Let’s take a look at reply tuples first. The path of the message passing will go from Player 1 to the Channel on the server, and back to Player 1.

Get hands-on with 1200+ tech skills courses.