Channels

Phoenix Channelsarrow-up-right are basically sockets. Senders broadcast messages about topics. Receivers subscribe to topics so that they can get those messages.

See Presence to extend functionality

mix phx.gen.channel [module_name] #user

Server

Already setup by default in endpoint.ex and user_socket.ex, most of the work is client side

To add current user to socket

lib/ss_web/channels/user_socket.ex

defmodule SsWeb.UserSocket do
  use Phoenix.Socket

  ## Channels
  channel "room:*", SsWeb.RoomChannel
  
  def connect(_params, socket, _connect_info) do
    IO.puts "CONNTECTING BABY"
    {:ok, assign(socket, :current_user, user)} #assign lets you store state(key-value) to this socket
  end
end

Whenever a client sends a message whose topic starts with "room:", it will be routed to our RoomChannel.

Channels

Like controllers, but have incoming and outgoing events and connections persist

Have join/3, terminate/2, handle_in/3, and handle_out/3

lib/ss_web/channels/room_channel.ex

broadcast will notify all clients on socket's topic and invoke their handle_out callback if defined for filtering/customization

When a client successfully establishes this connection, Phoenix Channels initializes an instance of %Phoenix.Socket{}. The channel server then retains awareness of this socket instance and maintains state within that instance via calls to socket.assign

Other Client

Last updated