Sending message to the client on join

Hi all,

I want to send welcome message to the client when it joins a channel. How can I accomplish this in my channel implementation?

Here is my channel implementation (default mix phx.gen.channel):


  def join("room:" <> room_id, payload, socket) do
    Logger.info "Request to join room"
    if authorized?(payload) do
      # send welcome message to new user
      {:ok, socket}
    else
      {:error, %{reason: "unauthorized"}}
    end
  end

Regards,
Ali

You can use the push command.

https://hexdocs.pm/phoenix/Phoenix.Channel.html#push/3

I would also recommend You to use some sort of after join… and leave join to it’s minimum…

def join("room:" <> room_id, payload, socket) do
  ...
  send(self(), :after_join)
  {:ok, socket}
end

def handle_info(:after_join, socket) do
  # do the real init here
  push(socket, "ping", %{ping: :os.system_time(:millisecond)})
  {:noreply, socket}
end

But for this simple case, that would work too

def join("room:" <> room_id, payload, socket) do
  Logger.info "Request to join room"
  if authorized?(payload) do
    # send welcome message to new user
    push(socket, "hello", %{hello: "world"})
    {:ok, socket}
  else
    {:error, %{reason: "unauthorized"}}
  end
end
4 Likes

Thanks a lot.