Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send message to specific socket with Phoenix

I have some socket with verification:

defmodule Test.UserSocket do
  use Phoenix.Socket

  ## Channels
  channel "user:*", Test.RoomChannel

  def connect(_params, socket) do
    case Phoenix.Token.verify(socket, "user",  _params["token"]) do
          {:ok, uid} ->
            {:ok, assign(socket, :user_id, uid)}
          {:error, _} ->
            :error
     end
  end

 def id(_socket), do: "user:#{_socket.assigns.user_id}"
end

And after connect socket named like user:#id

From the documentation I can send disconnect event Test.Endpoint.broadcast("users_socket:" <> user.id, "disconnect", %{})

Question: How to send custom event to socket by user:#id, it should be like a push notification to specific socket.

I tried Test.Endpoint.broadcast "user:1", "new:msg", %{user: "SYSTEM", body: "iex"} but it's doesn't work, because i can't listen "new:msg" on socket.

like image 411
user1156168 Avatar asked Dec 27 '15 17:12

user1156168


1 Answers

Copying Chris McCord's answer down from the comment:

You do it on a channel like you described. You don't need to verify in join/3 if you've already verified and assigned a current user on the socket in connect. Just check socket.assigns.user_id against whatever room the user is trying to join. Then you broadcast to that room Endpoint.broadcast "rooms:1", "new_msg", %{user: "SYSTEM", body: "iex"}

(Marking answer as community wiki since I don't want the rep points if anyone decides to upvote this. It's not my answer :) )

like image 80
Onorio Catenacci Avatar answered Oct 30 '22 17:10

Onorio Catenacci