elixir - how to send message to different user in phoenix framework chat app -
i working phoenix framework create different type chat app. in case, have chat rooms not functioning normal chat room.
every user has own room can join room using different devices (mobile, pc, other sources).
user has own room , user b has own room, these 2 members not connect single room in normal scenario in real world.
now user wants send message user b
message data eg:
from : :b message : test message
this snippet app.js
used connect user's specific room :
let room = socket.channel("room:"+ user, {}) room.on("presence_state", state => { presences = presence.syncstate(presences, status) console.log(presences) render(presences) })
this snippet back-end join room function
/web/channel/roomchannel.ex
def join("room:" <> _user, _, socket) send self(), :after_join {:ok, socket} end
but stuck in middle because cannot find way send messages between users. eg: cannot identify way deliver user a's message user b using specific scenario
this basic architect of chat app :
this rest of code in roomchannel file
def handle_info(:after_join, socket) presence.track(socket, socket.assigns.user, %{ online_at: :os.system_time(:millisecond) }) push socket, "presence_state", presence.list(socket) {:noreply, socket} end def handle_in("message:new", message, socket) broadcast! socket, "message:new", %{ user: socket.assigns.user, body: message, timestamp: :os.system_time(:millisecond) } milisecondstime = :os.system_time(:millisecond) [room, user] = string.split(map.get(socket, :topic), ":") data = poison.encode!(%{"created_at" => :os.system_time(:millisecond), "updated_at" => :os.system_time(:millisecond), "uuid" => uuid.uuid1(), "date" => :os.system_time(:millisecond), "from" => user, "to" => user, "message" => message}) redix.command(:redix, ["set", uuid.uuid1(), data]) {:noreply, socket} end
can show me way can pass messages between user's chat rooms?
i'm using redis
store data , this basic chat app following developer.
look phoenix.endpoint.broadcast
can send message given topic using broadcast/3
function
another way can go subscribe each user unique private topic when user joins channel join
function
def join("room:" <> _user, _, socket) send self(), :after_join myapp.endpoint.subscribe("private-room:" <> user) # subscribe connecting client private room {:ok, socket} end
then in handle_in("message:new",message, socket)
extract receipient user id message payload , call
endpoint.broadcast
def handle_in("message:new", message, socket) myapp.endpoint.broadcast!("private-room:" <> to_user , "message:new",%{ user: socket.assigns.user, body: message, timestamp: :os.system_time(:millisecond) }) #sends message connected clients to_user {:noreply, socket} end
Comments
Post a Comment