Channels

Channels are Phoenix's abstraction of WebSockets:

defmodule MyAppWeb.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
end

Scaling across multiple servers

Channels use Phoenix.PubSub under the hood to broadcast messages between processes. By default, it's local to the node and can be configured for distributed systems,

In config.exs:

config :my_app, MyAppWeb.Endpoint,
  pubsub_server: MyApp.PubSub

config :my_app, MyApp.PubSub,
  adapter: Phoenix.PubSub.Redis,
  url: "redis://localhost:6379"