凤凰频道:向特定客户发送推送 [英] Phoenix channels: send push to a particular client
问题描述
我正在尝试使用长寿凤凰重新实现whatsapp的功能.我在解决以下问题时遇到了问题:如果聊天室中的所有人都收到了消息,我想发送消息状态为已接收"的所有者,以便他可以显示双勾号.但是,您如何向一个特定的客户广播?
Hi I am trying to reimplement whatsapp functionality using elixir phoenix. I am having a problem figuring out the following: if all people in the chat room has received the message, I want to send the owner of the message status "received" so that he can show double tick sign. However how do you broadcast to one particular client?
推荐答案
您可以通过每个用户的主题来解决此问题,这可以通过模式匹配轻松实现,还请注意安全性验证:
You can solve this via topic per user, this can be easily implemented by pattern matching, notice the security validation also:
def join("users:" <> user_id, _params, socket) do
{user_id, _} = Integer.parse(user_id)
%{id: id} = socket.assigns[:user]
#prevent connection to solo channel of other users, but allow in development
case id == user_id || Mix.env == :dev do
true ->
{:ok, socket}
false ->
{:error, "This is not your solo channel!"}
end
end
就像当用户在以下位置将套接字连接到
As you would have stored the user from Repo.get
when the user connect to the socket at:
defmodule MyApp.UserSocket do
use Phoenix.Socket
def connect(%{"token" => token}, socket) do
case Phoenix.Token.verify(socket, "user", token, max_age: 1209600) do
{:ok, user_id} ->
socket = assign(socket, :user, Repo.get!(User, user_id))
{:ok, socket}
{:error, _} -> #...
end
end
end
最后,您可以通过套接字上下文向特定用户发送消息,如下所示:
And finally, you can send messages to a specific user out of socket context as:
YourAll.Endpoint.broadcast user_topic, "message", %{details: "etc"}
要测试性能,这是一个非常有用的会议,其中Gary Rennie展示了如何使用Tsung工具对WebSocket进行基准测试.
To test the performance, this is a very informative session in which Gary Rennie shows how to benchmark WebSockets using Tsung tool.
这篇关于凤凰频道:向特定客户发送推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!