How to send a message to a specific socket with Phoenix

I have a socket with validation:

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 connecting the socket named as user:#id

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

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

I tried Test.Endpoint.broadcast "user:1", "new:msg", %{user: "SYSTEM", body: "iex"} , but it does not work because I can not listen to "new: msg" in the socket.

+8
elixir phoenix-framework
source share
2 answers

Copy Chris McCord in response to comment:

You do this on the channel as described. You do not need to check in join/3 if you have already checked and assigned the current user on the socket to connect. Just check socket.assigns.user_id for any room the user is trying to join. Then you broadcast Endpoint.broadcast "rooms:1", "new_msg", %{user: "SYSTEM", body: "iex"} into this room

(Mark the answer as a wiki community, as I do not want the reputation to indicate if someone decides to double-check this. This is not my answer :))

+2
source share

Thanks for the answer. Therefore, we work only on "indoor" bases. And my sources will look like this: def join ("user:" <> _uid, message, socket) do if _uid == socket.assigns.user_id do {: ok, socket} else {: error,% {reason: " unauthorized "}} end end

you do not need to check the user ID again, since you have already defined the logic in ConnectionSource #, if the user is not authenticated, he receives a message saying that he is not authorized, what you can do is use userId to check if the user has permission to watching a specific channel, for example

 def join("rooms:some_private_room", message, socket) do if socket.assigns.user_id do {:ok, socket} else # kick him out he is not allowed here {:error, %{reason: "unauthorized"}} end end 
0
source share

All Articles