广播时如何排除某些用户? [英] How to exclude some users when broadcast?

查看:83
本文介绍了广播时如何排除某些用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于broadcast!将向除发件人之外的所有订阅主题的用户发送消息,是否可以向某些用户发送消息?或发送给特定用户?

As broadcast! will send message to all users subscribed to topic except sender, is it possible to except certain users? or send to a specific user?

我需要用户将事件推送到某个频道,但只有管理员用户会收到消息,其他用户将不会收到消息,而只会发送消息.

I need users to push events to a channel, but only admin user will receive messages, other users will not receive messages, but only send them.

我可以在客户端解决此问题,只需让用户忽略通过broadcast!收到的消息,而仅由管理员用户处理收到的消息,但是如何在服务器端解决此问题?

I can solve this at client side by simply let users ignore messages they receive via broadcast! and only admin user process received messages, but how to solve this at server side?

简而言之,加入一个频道,但只能读取或仅发送吗?

In short, join a channel, but can read only, or send only?

推荐答案

如果按照 https://hexdocs.pm/phoenix/Phoenix.Token.html

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

然后,您可以在您的频道此处记录的handle_out函数中检查用户的管理员状态. :

Then you can check for the users admin status in the handle_out function for your channel documented here:

defmodule HelloPhoenix.RoomChannel do
  intercept ["new_msg"]
  ...
  def handle_out("new_msg", payload, socket) do
    if socket.assigns.user.admin do
      push socket, "new_msg", payload
    end
    {:noreply, socket}
  end
end

根据您的邮件数量和管理员数量,您可以考虑为这些事件设置一个特定于管理员的渠道.这样可以防止将消息发送给非管理员用户的进程,而不是简单地忽略它们.

Depending on your volume of messages and number of admins, you may consider having an admin-specific channel for these events. This would prevent messages being sent to processes for non-admin users instead of simply ignoring them.

这篇关于广播时如何排除某些用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆