{"__v":0,"_id":"5777c9635b2b430e00b982b6","category":{"version":"5777c9635b2b430e00b982a5","project":"54348ec95b10711400c6c445","_id":"5777c9635b2b430e00b982a7","__v":0,"sync":{"url":"","isSync":false},"reference":false,"createdAt":"2014-10-09T04:18:04.869Z","from_sync":false,"order":1,"slug":"guides","title":"Guides"},"parentDoc":null,"project":"54348ec95b10711400c6c445","user":"5435e00ad7d8700800bbec51","version":{"__v":1,"_id":"5777c9635b2b430e00b982a5","project":"54348ec95b10711400c6c445","createdAt":"2016-07-02T14:02:11.084Z","releaseDate":"2016-07-02T14:02:11.084Z","categories":["5777c9635b2b430e00b982a6","5777c9635b2b430e00b982a7","5777c9635b2b430e00b982a8","5777c9635b2b430e00b982a9","5777c9635b2b430e00b982aa"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"1.2.0","version":"1.2.0"},"updates":["54d2b4d85616470d0013cbf0","550cbf9d25677e0d00b62479","552133cd86177c0d00812bf3","553ba1f18449f80d006d6376","555180e7bcb05a0d00693097","556b931c61c7f40d001ce021","559689ba46e90a0d00eb68fd","55e24fbc171b1a0d0066ae1c","55e30806f7b2dd170066707f","55e49272830ec32300e1a33d","55f18b2e5fe76419007dc70c","55f9d567d6f4370d001d9962","5661ad3bbb77350d0073266a","5669988ffc5abf2300afe7ec","568940375422830d0024ba54","56d1c27b2baeae0b00aa5033","56f4e364757a450e0072d70c"],"createdAt":"2014-12-03T22:08:06.734Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"never","params":[],"url":""},"isReference":false,"order":11,"body":"Channels are a really exciting and powerful part of Phoenix that allow us to easily add soft-realtime features to our applications. Channels are based on a simple idea - sending and receiving messages. Senders broadcast messages about topics. Receivers subscribe to topics so that they can get those messages. Senders and receivers can switch roles on the same topic at any time.\n\nSince Elixir is based on message passing, you may wonder why we need this extra mechanism to send and receive messages. With Channels, neither senders nor receivers have to be Elixir processes. They can be anything that we can teach to communicate over a Channel - a JavaScript client, an iOS app, another Phoenix application, our watch. Also, messages broadcast over a Channel may have many receivers. Elixir processes communicate one to one.\n\nThe word \"Channel\" is really shorthand for a layered system with a number of components. Let's take a quick look at them now so we can see the big picture a little better.\n\n#### The Moving Parts\n\n- Socket Handlers\n\nPhoenix holds a single connection to the server and multiplexes your channel sockets over that one connection. Socket handlers, such as `web/channels/user_socket.ex`, are modules that authenticate and identify a socket connection and allow you to set default socket assigns for use in all channels.\n\n- Channel Routes\n\nThese are defined in Socket handlers, such as `web/channels/user_socket.ex`, which makes them distinct from other routes. They match on the topic string and dispatch matching requests to the given Channel module. The star character `*` acts as a wildcard matcher, so in the following example route, requests for `sample_topic:pizza` and `sample_topic:oranges` would both be dispatched to the `SampleTopicChannel`.\n\n```elixir\nchannel \"sample_topic:*\", HelloPhoenix.SampleTopicChannel\n```\n\n- Channels\n\nChannels handle events from clients, so they are similar to Controllers, but there are two key differences. Channel events can go both directions - incoming and outgoing. Channel connections also persist beyond a single request/response cycle. Channels are the highest level abstraction for realtime communication components in Phoenix.\n\nEach Channel will implement one or more clauses of each of these four callback functions - `join/3`, `terminate/2`, `handle_in/3`, and `handle_out/3`.\n\n- PubSub\n\nThe Phoenix PubSub layer consists of the `Phoenix.PubSub` module and a variety of modules for different adapters and their `GenServer`s. These modules contain functions which are the nuts and bolts of organizing Channel communication - subscribing to topics, unsubscribing from topics, and broadcasting messages on a topic.\n\nWe can also define our own PubSub adapters if we need to. Please see the [Phoenix.PubSub docs](http://hexdocs.pm/phoenix/Phoenix.PubSub.html) for more information.\n\nIt is worth noting that these modules are intended for Phoenix's internal use. Channels use them under the hood to do much of their work. As end users, we shouldn't have any need to use them directly in our applications.\n\n- Messages\n\nThe `Phoenix.Socket.Message` module defines a struct with the following keys which denotes a valid message. From the [Phoenix.Socket.Message docs](http://hexdocs.pm/phoenix/Phoenix.Socket.Message.html).\n  - `topic` - The string topic or topic:subtopic pair namespace, for example “messages”, “messages:123”\n  - `event` - The string event name, for example “phx_join”\n  - `payload` - The message payload\n  - `ref` - The unique string ref\n\n- Topics\n\nTopics are string identifiers - names that the various layers use in order to make sure messages end up in the right place. As we saw above, topics can use wildcards. This allows for a useful \"topic:subtopic\" convention. Often, you'll compose topics using record IDs from your model layer, such as `\"users:123\"`.\n\n- Transports\n\nThe transport layer is where the rubber meets the road. The `Phoenix.Channel.Transport` module handles all the message dispatching into and out of a Channel.\n\n- Transport Adapters\n\nThe default transport mechanism is via WebSockets which will fall back to LongPolling if WebSockets are not available. Other transport adapters are possible, and we can write our own if we follow the adapter contract. Please see `Phoenix.Transports.WebSocket` for an example.\n\n- Client Libraries\n\nPhoenix currently ships with its own JavaScript client. [iOS](https://github.com/davidstump/SwiftPhoenixClient), [Android](https://github.com/eoinsha/JavaPhoenixChannels), and [C#](https://github.com/jfis/dn-phoenix) clients have been released with Phoenix 1.0.\n\n## Tying it all together\nLet's tie all these ideas together by building a simple chat application. After [generating a new Phoenix application](http://www.phoenixframework.org/docs/up-and-running) we'll see that the endpoint is already set up for us in `lib/hello_phoenix/endpoint.ex`:\n\n```elixir\ndefmodule HelloPhoenix.Endpoint do\n  use Phoenix.Endpoint, otp_app: :hello_phoenix\n\n  socket \"/socket\", HelloPhoenix.UserSocket\n  ...\nend\n```\n\nIn `web/channels/user_socket.ex`, the `HelloPhoenix.UserSocket` we pointed to in our endpoint has already been created when we generated our application. We need to make sure messages get routed to the correct channel. To do that, we'll uncomment the \"room:*\" channel definition:\n\n```elixir\ndefmodule HelloPhoenix.UserSocket do\n  use Phoenix.Socket\n\n  ## Channels\n  channel \"room:*\", HelloPhoenix.RoomChannel\n  ...\n```\n\nNow, whenever a client sends a message whose topic starts with `\"room:\"`, it will be routed to our RoomChannel. Next, we'll define a `HelloPhoenix.RoomChannel` module to manage our chat room messages.\n\n### Joining Channels\n\nThe first priority of your channels is to authorize clients to join a given topic. For authorization, we must implement `join/3` in `web/channels/room_channel.ex`.\n\n```elixir\ndefmodule HelloPhoenix.RoomChannel do\n  use Phoenix.Channel\n\n  def join(\"room:lobby\", _message, socket) do\n    {:ok, socket}\n  end\n  def join(\"room:\" <> _private_room_id, _params, _socket) do\n    {:error, %{reason: \"unauthorized\"}}\n  end\nend\n```\n\nFor our chat app, we'll allow anyone to join the `\"room:lobby\"` topic, but any other room will be considered private and special authorization, say from a database, will be required. We won't worry about private chat room for this exercise, but feel free to explore after we finish. To authorize the socket to join a topic, we return `{:ok, socket}` or `{:ok, reply, socket}`. To deny access, we return `{:error, reply}`. More information about authorization with tokens can be found in the [`Phoenix.Token` documentation](http://hexdocs.pm/phoenix/Phoenix.Token.html).\n\nWith our channel in place, let's get the client and server talking.\n\nPhoenix projects come with [Brunch](http://www.phoenixframework.org/docs/static-assets) built in, unless disabled with the `--no-brunch` option when you run `mix phoenix.new`.\n\nIf you are using brunch, there's some code in `web/static/js/socket.js` that defines a simple client based on the socket implementation that ships with Phoenix.\n\nWe can use that library to connect to our socket and join our channel, we just need to set our room name to \"room:lobby\" in that file.\n\n```javascript\n// web/static/js/socket.js\n...\nsocket.connect()\n\n// Now that you are connected, you can join channels with a topic:\nlet channel = socket.channel(\"room:lobby\", {})\nchannel.join()\n  .receive(\"ok\", resp => { console.log(\"Joined successfully\", resp) })\n  .receive(\"error\", resp => { console.log(\"Unable to join\", resp) })\n\nexport default socket\n```\n\nAfter that, we need to make sure `web/static/js/socket.js` gets imported into our application javascript file. To do that, uncomment the last line in `web/static/js/app.js`.\n\n```javascript\n...\nimport socket from \"./socket\"\n```\n\nSave the file and your browser should auto refresh, thanks to the Phoenix live reloader. If everything worked, we should see \"Joined successfully\" in the browser's JavaScript console. Our client and server are now talking over a persistent connection. Now let's make it useful by enabling chat.\n\nIn `web/templates/page/index.html.eex`, we'll replace the existing code with a container to hold our chat messages, and an input field to send them:\n\n```html\n<div id=\"messages\"></div>\n<input id=\"chat-input\" type=\"text\"></input>\n```\n\nWe'll also add jQuery to our application layout in `web/templates/layout/app.html.eex`:\n\n```html\n  ...\n    <%= render :::at:::view_module, @view_template, assigns %>\n\n  </div> <!-- /container -->\n  <script src=\"//code.jquery.com/jquery-1.12.4.min.js\"></script>\n  <script src=\"<%= static_path(@conn, \"/js/app.js\") %>\"></script>\n</body>\n```\n\nNow let's add a couple of event listeners to `web/static/js/socket.js`:\n\n```javascript\n...\nlet channel           = socket.channel(\"room:lobby\", {})\nlet chatInput         = $(\"#chat-input\")\nlet messagesContainer = $(\"#messages\")\n\nchatInput.on(\"keypress\", event => {\n  if(event.keyCode === 13){\n    channel.push(\"new_msg\", {body: chatInput.val()})\n    chatInput.val(\"\")\n  }\n})\n\nchannel.join()\n  .receive(\"ok\", resp => { console.log(\"Joined successfully\", resp) })\n  .receive(\"error\", resp => { console.log(\"Unable to join\", resp) })\n\nexport default socket\n```\n\nAll we had to do is detect that enter was pressed and then `push` an event over the channel with the message body. We named the event \"new_msg\". With this in place, let's handle the other piece of a chat application where we listen for new messages and append them to our messages container.\n\n```javascript\n...\nlet channel           = socket.channel(\"room:lobby\", {})\nlet chatInput         = $(\"#chat-input\")\nlet messagesContainer = $(\"#messages\")\n\nchatInput.on(\"keypress\", event => {\n  if(event.keyCode === 13){\n    channel.push(\"new_msg\", {body: chatInput.val()})\n    chatInput.val(\"\")\n  }\n})\n\nchannel.on(\"new_msg\", payload => {\n  messagesContainer.append(`<br/>[${Date()}] ${payload.body}`)\n})\n\nchannel.join()\n  .receive(\"ok\", resp => { console.log(\"Joined successfully\", resp) })\n  .receive(\"error\", resp => { console.log(\"Unable to join\", resp) })\n\nexport default socket\n```\n\nWe listen for the `\"new_msg\"` event using `channel.on`, and then append the message body to the DOM. Now let's handle the incoming and outgoing events on the server to complete the picture.\n\n### Incoming Events\nWe handle incoming events with `handle_in/3`. We can pattern match on the event names, like `\"new_msg\"`, and then grab the payload that the client passed over the channel. For our chat application, we simply need to notify all other `room:lobby` subscribers of the new message with `broadcast!/3`.\n\n```elixir\ndefmodule HelloPhoenix.RoomChannel do\n  use Phoenix.Channel\n\n  def join(\"room:lobby\", _message, socket) do\n    {:ok, socket}\n  end\n  def join(\"room:\" <> _private_room_id, _params, _socket) do\n    {:error, %{reason: \"unauthorized\"}}\n  end\n\n  def handle_in(\"new_msg\", %{\"body\" => body}, socket) do\n    broadcast! socket, \"new_msg\", %{body: body}\n    {:noreply, socket}\n  end\n\n  def handle_out(\"new_msg\", payload, socket) do\n    push socket, \"new_msg\", payload\n    {:noreply, socket}\n  end\nend\n```\n\n`broadcast!/3` will notify all joined clients on this `socket`'s topic and invoke their `handle_out/3` callbacks. `handle_out/3` isn't a required callback, but it allows us to customize and filter broadcasts before they reach each client. By default, `handle_out/3` is implemented for us and simply pushes the message on to the client, just like our definition. We included it here because hooking into outgoing events allows for powerful message customization and filtering. Let's see how.\n\n#### Intercepting Outgoing Events\nWe won't implement this for our application, but imagine our chat app allowed users to ignore messages about new users joining a room. We could implement that behavior like this where we explicitly tell Phoenix which outgoing event we want to intercept and then define a `handle_out/3` callback for those events. (Of course, this assumes that we have a `User` model with an `ignoring?/2` function, and that we pass a user in via the `assigns` map.)\n\n```elixir\nintercept [\"user_joined\"]\n\ndef handle_out(\"user_joined\", msg, socket) do\n  if User.ignoring?(socket.assigns[:user], msg.user_id) do\n    {:noreply, socket}\n  else\n    push socket, \"user_joined\", msg\n    {:noreply, socket}\n  end\nend\n```\n\nThat's all there is to our basic chat app. Fire up multiple browser tabs and you should see your messages being pushed and broadcasted to all windows!\n\n#### Socket Assigns\n\nSimilar to connection structs, `%Plug.Conn{}`, it is possible to assign values to a channel socket. `Phoenix.Socket.assign/3` is conveniently imported into a channel module as `assign/3`:\n\n```elixir\nsocket = assign(socket, :user, msg[\"user\"])\n```\n\nSockets store assigned values as a map in `socket.assigns`.\n\n#### Fault Tolerance and Reliability Guarantees\n\nServers restart, networks split, and clients lose connectivity. In order to design robust systems, we need to understand how Phoenix responds to these events and what guarantees it offers.\n\n- Handling Reconnection\n\nClients subscribe to topics, and Phoenix stores those subscriptions in an in-memory ETS table. If a channel crashes, the clients will need to reconnect to the topics they had previously subscribed to. Fortunately, the Phoenix JavaScript client knows how to do this. The server will notify all the clients of the crash. This will trigger each client's `Channel.onError` callback. The clients will attempt to reconnect to the server using an exponential back off strategy. Once they reconnect, they'll attempt to rejoin the topics they had previously subscribed to. If they are successful, they'll start receiving messages from those topics as before.\n\n- Resending Client Messages\n\nChannel clients queue outgoing messages into a `PushBuffer`, and send them to server when there is a connection. If no connection is available, the client holds on to the messages until it can establish a new connection. With no connection, the client will hold the messages in memory until it establishes a connection, or until it receives a `timeout` event. The default timeout is set to 5000 milliseconds. The client won't persist the messages in the browser's local storage, so if the browser tab closes, the messages will be gone.\n\n- Resending Server Messages\n\nPhoenix uses an at-most-once strategy when sending messages to clients. If the client is offline and misses the message, Phoenix won't resend it. Phoenix doesn't persist messages on the server. If the server restarts, unsent messages will be gone. If our application needs stronger guarantees around message delivery, we'll need to write that code ourselves. Common approaches involve persisting messages on the server and having clients request missing messages. For an example, see Chris McCord's Phoenix training: [client code](https://github.com/chrismccord/elixirconf_training/blob/master/web/static/js/app.js#L38-L39) and [server code](https://github.com/chrismccord/elixirconf_training/blob/master/web/channels/document_channel.ex#L13-L19).\n\n\n#### Example Application\nTo see an example of the application we just built, checkout this project (https://github.com/chrismccord/phoenix_chat_example).\n\nYou can also see a live demo at (http://phoenixchat.herokuapp.com/).","excerpt":"","slug":"channels","type":"basic","title":"Channels"}
Channels are a really exciting and powerful part of Phoenix that allow us to easily add soft-realtime features to our applications. Channels are based on a simple idea - sending and receiving messages. Senders broadcast messages about topics. Receivers subscribe to topics so that they can get those messages. Senders and receivers can switch roles on the same topic at any time. Since Elixir is based on message passing, you may wonder why we need this extra mechanism to send and receive messages. With Channels, neither senders nor receivers have to be Elixir processes. They can be anything that we can teach to communicate over a Channel - a JavaScript client, an iOS app, another Phoenix application, our watch. Also, messages broadcast over a Channel may have many receivers. Elixir processes communicate one to one. The word "Channel" is really shorthand for a layered system with a number of components. Let's take a quick look at them now so we can see the big picture a little better. #### The Moving Parts - Socket Handlers Phoenix holds a single connection to the server and multiplexes your channel sockets over that one connection. Socket handlers, such as `web/channels/user_socket.ex`, are modules that authenticate and identify a socket connection and allow you to set default socket assigns for use in all channels. - Channel Routes These are defined in Socket handlers, such as `web/channels/user_socket.ex`, which makes them distinct from other routes. They match on the topic string and dispatch matching requests to the given Channel module. The star character `*` acts as a wildcard matcher, so in the following example route, requests for `sample_topic:pizza` and `sample_topic:oranges` would both be dispatched to the `SampleTopicChannel`. ```elixir channel "sample_topic:*", HelloPhoenix.SampleTopicChannel ``` - Channels Channels handle events from clients, so they are similar to Controllers, but there are two key differences. Channel events can go both directions - incoming and outgoing. Channel connections also persist beyond a single request/response cycle. Channels are the highest level abstraction for realtime communication components in Phoenix. Each Channel will implement one or more clauses of each of these four callback functions - `join/3`, `terminate/2`, `handle_in/3`, and `handle_out/3`. - PubSub The Phoenix PubSub layer consists of the `Phoenix.PubSub` module and a variety of modules for different adapters and their `GenServer`s. These modules contain functions which are the nuts and bolts of organizing Channel communication - subscribing to topics, unsubscribing from topics, and broadcasting messages on a topic. We can also define our own PubSub adapters if we need to. Please see the [Phoenix.PubSub docs](http://hexdocs.pm/phoenix/Phoenix.PubSub.html) for more information. It is worth noting that these modules are intended for Phoenix's internal use. Channels use them under the hood to do much of their work. As end users, we shouldn't have any need to use them directly in our applications. - Messages The `Phoenix.Socket.Message` module defines a struct with the following keys which denotes a valid message. From the [Phoenix.Socket.Message docs](http://hexdocs.pm/phoenix/Phoenix.Socket.Message.html). - `topic` - The string topic or topic:subtopic pair namespace, for example “messages”, “messages:123” - `event` - The string event name, for example “phx_join” - `payload` - The message payload - `ref` - The unique string ref - Topics Topics are string identifiers - names that the various layers use in order to make sure messages end up in the right place. As we saw above, topics can use wildcards. This allows for a useful "topic:subtopic" convention. Often, you'll compose topics using record IDs from your model layer, such as `"users:123"`. - Transports The transport layer is where the rubber meets the road. The `Phoenix.Channel.Transport` module handles all the message dispatching into and out of a Channel. - Transport Adapters The default transport mechanism is via WebSockets which will fall back to LongPolling if WebSockets are not available. Other transport adapters are possible, and we can write our own if we follow the adapter contract. Please see `Phoenix.Transports.WebSocket` for an example. - Client Libraries Phoenix currently ships with its own JavaScript client. [iOS](https://github.com/davidstump/SwiftPhoenixClient), [Android](https://github.com/eoinsha/JavaPhoenixChannels), and [C#](https://github.com/jfis/dn-phoenix) clients have been released with Phoenix 1.0. ## Tying it all together Let's tie all these ideas together by building a simple chat application. After [generating a new Phoenix application](http://www.phoenixframework.org/docs/up-and-running) we'll see that the endpoint is already set up for us in `lib/hello_phoenix/endpoint.ex`: ```elixir defmodule HelloPhoenix.Endpoint do use Phoenix.Endpoint, otp_app: :hello_phoenix socket "/socket", HelloPhoenix.UserSocket ... end ``` In `web/channels/user_socket.ex`, the `HelloPhoenix.UserSocket` we pointed to in our endpoint has already been created when we generated our application. We need to make sure messages get routed to the correct channel. To do that, we'll uncomment the "room:*" channel definition: ```elixir defmodule HelloPhoenix.UserSocket do use Phoenix.Socket ## Channels channel "room:*", HelloPhoenix.RoomChannel ... ``` Now, whenever a client sends a message whose topic starts with `"room:"`, it will be routed to our RoomChannel. Next, we'll define a `HelloPhoenix.RoomChannel` module to manage our chat room messages. ### Joining Channels The first priority of your channels is to authorize clients to join a given topic. For authorization, we must implement `join/3` in `web/channels/room_channel.ex`. ```elixir defmodule HelloPhoenix.RoomChannel do use Phoenix.Channel def join("room:lobby", _message, socket) do {:ok, socket} end def join("room:" <> _private_room_id, _params, _socket) do {:error, %{reason: "unauthorized"}} end end ``` For our chat app, we'll allow anyone to join the `"room:lobby"` topic, but any other room will be considered private and special authorization, say from a database, will be required. We won't worry about private chat room for this exercise, but feel free to explore after we finish. To authorize the socket to join a topic, we return `{:ok, socket}` or `{:ok, reply, socket}`. To deny access, we return `{:error, reply}`. More information about authorization with tokens can be found in the [`Phoenix.Token` documentation](http://hexdocs.pm/phoenix/Phoenix.Token.html). With our channel in place, let's get the client and server talking. Phoenix projects come with [Brunch](http://www.phoenixframework.org/docs/static-assets) built in, unless disabled with the `--no-brunch` option when you run `mix phoenix.new`. If you are using brunch, there's some code in `web/static/js/socket.js` that defines a simple client based on the socket implementation that ships with Phoenix. We can use that library to connect to our socket and join our channel, we just need to set our room name to "room:lobby" in that file. ```javascript // web/static/js/socket.js ... socket.connect() // Now that you are connected, you can join channels with a topic: let channel = socket.channel("room:lobby", {}) channel.join() .receive("ok", resp => { console.log("Joined successfully", resp) }) .receive("error", resp => { console.log("Unable to join", resp) }) export default socket ``` After that, we need to make sure `web/static/js/socket.js` gets imported into our application javascript file. To do that, uncomment the last line in `web/static/js/app.js`. ```javascript ... import socket from "./socket" ``` Save the file and your browser should auto refresh, thanks to the Phoenix live reloader. If everything worked, we should see "Joined successfully" in the browser's JavaScript console. Our client and server are now talking over a persistent connection. Now let's make it useful by enabling chat. In `web/templates/page/index.html.eex`, we'll replace the existing code with a container to hold our chat messages, and an input field to send them: ```html <div id="messages"></div> <input id="chat-input" type="text"></input> ``` We'll also add jQuery to our application layout in `web/templates/layout/app.html.eex`: ```html ... <%= render @view_module, @view_template, assigns %> </div> <!-- /container --> <script src="//code.jquery.com/jquery-1.12.4.min.js"></script> <script src="<%= static_path(@conn, "/js/app.js") %>"></script> </body> ``` Now let's add a couple of event listeners to `web/static/js/socket.js`: ```javascript ... let channel = socket.channel("room:lobby", {}) let chatInput = $("#chat-input") let messagesContainer = $("#messages") chatInput.on("keypress", event => { if(event.keyCode === 13){ channel.push("new_msg", {body: chatInput.val()}) chatInput.val("") } }) channel.join() .receive("ok", resp => { console.log("Joined successfully", resp) }) .receive("error", resp => { console.log("Unable to join", resp) }) export default socket ``` All we had to do is detect that enter was pressed and then `push` an event over the channel with the message body. We named the event "new_msg". With this in place, let's handle the other piece of a chat application where we listen for new messages and append them to our messages container. ```javascript ... let channel = socket.channel("room:lobby", {}) let chatInput = $("#chat-input") let messagesContainer = $("#messages") chatInput.on("keypress", event => { if(event.keyCode === 13){ channel.push("new_msg", {body: chatInput.val()}) chatInput.val("") } }) channel.on("new_msg", payload => { messagesContainer.append(`<br/>[${Date()}] ${payload.body}`) }) channel.join() .receive("ok", resp => { console.log("Joined successfully", resp) }) .receive("error", resp => { console.log("Unable to join", resp) }) export default socket ``` We listen for the `"new_msg"` event using `channel.on`, and then append the message body to the DOM. Now let's handle the incoming and outgoing events on the server to complete the picture. ### Incoming Events We handle incoming events with `handle_in/3`. We can pattern match on the event names, like `"new_msg"`, and then grab the payload that the client passed over the channel. For our chat application, we simply need to notify all other `room:lobby` subscribers of the new message with `broadcast!/3`. ```elixir defmodule HelloPhoenix.RoomChannel do use Phoenix.Channel def join("room:lobby", _message, socket) do {:ok, socket} end def join("room:" <> _private_room_id, _params, _socket) do {:error, %{reason: "unauthorized"}} end def handle_in("new_msg", %{"body" => body}, socket) do broadcast! socket, "new_msg", %{body: body} {:noreply, socket} end def handle_out("new_msg", payload, socket) do push socket, "new_msg", payload {:noreply, socket} end end ``` `broadcast!/3` will notify all joined clients on this `socket`'s topic and invoke their `handle_out/3` callbacks. `handle_out/3` isn't a required callback, but it allows us to customize and filter broadcasts before they reach each client. By default, `handle_out/3` is implemented for us and simply pushes the message on to the client, just like our definition. We included it here because hooking into outgoing events allows for powerful message customization and filtering. Let's see how. #### Intercepting Outgoing Events We won't implement this for our application, but imagine our chat app allowed users to ignore messages about new users joining a room. We could implement that behavior like this where we explicitly tell Phoenix which outgoing event we want to intercept and then define a `handle_out/3` callback for those events. (Of course, this assumes that we have a `User` model with an `ignoring?/2` function, and that we pass a user in via the `assigns` map.) ```elixir intercept ["user_joined"] def handle_out("user_joined", msg, socket) do if User.ignoring?(socket.assigns[:user], msg.user_id) do {:noreply, socket} else push socket, "user_joined", msg {:noreply, socket} end end ``` That's all there is to our basic chat app. Fire up multiple browser tabs and you should see your messages being pushed and broadcasted to all windows! #### Socket Assigns Similar to connection structs, `%Plug.Conn{}`, it is possible to assign values to a channel socket. `Phoenix.Socket.assign/3` is conveniently imported into a channel module as `assign/3`: ```elixir socket = assign(socket, :user, msg["user"]) ``` Sockets store assigned values as a map in `socket.assigns`. #### Fault Tolerance and Reliability Guarantees Servers restart, networks split, and clients lose connectivity. In order to design robust systems, we need to understand how Phoenix responds to these events and what guarantees it offers. - Handling Reconnection Clients subscribe to topics, and Phoenix stores those subscriptions in an in-memory ETS table. If a channel crashes, the clients will need to reconnect to the topics they had previously subscribed to. Fortunately, the Phoenix JavaScript client knows how to do this. The server will notify all the clients of the crash. This will trigger each client's `Channel.onError` callback. The clients will attempt to reconnect to the server using an exponential back off strategy. Once they reconnect, they'll attempt to rejoin the topics they had previously subscribed to. If they are successful, they'll start receiving messages from those topics as before. - Resending Client Messages Channel clients queue outgoing messages into a `PushBuffer`, and send them to server when there is a connection. If no connection is available, the client holds on to the messages until it can establish a new connection. With no connection, the client will hold the messages in memory until it establishes a connection, or until it receives a `timeout` event. The default timeout is set to 5000 milliseconds. The client won't persist the messages in the browser's local storage, so if the browser tab closes, the messages will be gone. - Resending Server Messages Phoenix uses an at-most-once strategy when sending messages to clients. If the client is offline and misses the message, Phoenix won't resend it. Phoenix doesn't persist messages on the server. If the server restarts, unsent messages will be gone. If our application needs stronger guarantees around message delivery, we'll need to write that code ourselves. Common approaches involve persisting messages on the server and having clients request missing messages. For an example, see Chris McCord's Phoenix training: [client code](https://github.com/chrismccord/elixirconf_training/blob/master/web/static/js/app.js#L38-L39) and [server code](https://github.com/chrismccord/elixirconf_training/blob/master/web/channels/document_channel.ex#L13-L19). #### Example Application To see an example of the application we just built, checkout this project (https://github.com/chrismccord/phoenix_chat_example). You can also see a live demo at (http://phoenixchat.herokuapp.com/).