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.
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 :) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With