如何在 asp.net core SignalR 中迭代用户? [英] How to iterate over users in asp.net core SignalR?

查看:22
本文介绍了如何在 asp.net core SignalR 中迭代用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 .net core 上的 SignalR 应用程序中,我有一段类似于以下的工作代码:

In a SignalR application on .net core, I have a working piece of code similar to the following:

public Task SendPrivateMessage(string user, string message)
{
    var sender = Context.User.Claims.FirstOrDefault(cl => cl.Type == "username")?.Value;
    return Clients.User(user)
                  .SendAsync("ReceiveMessage", $"Message from {sender}: {message}");
}

这会从当前连接的用户向指定用户发送消息.

This sends a message from the currently connected user, to the specified user.

现在我想向每个连接的用户发送一条单独的消息;类似于以下概念:

Now I'd like to send an individual message to every user connected; something like the following concept:

public Task UpdateMessageStatus()
{
    foreach(client in Clients.Users)
    {
         var nrOfMessages = GetMessageCount();
         client.SendAsync($"You have {nrOfMessages} messages.");
    }
}

我怎样才能做到这一点;即我如何遍历连接的用户,并向他们每个人发送单独的消息?

How can I achieve this; i.e. how can I iterate over connected users, and send individual messages to each of them?

编辑/澄清

如前所述,我需要向每个连接的用户发送个人(即专门的)消息,因此使用 Clients.All 不是一种选择,因为这只能是用于向所有连接的用户发送相同的消息.

As mentioned, I needed to send individual (i.e. specialized) messages to each connected user, so using Clients.All was not an option, as that can only be used to send the same message to all connected users.

我最终做了一些类似于 Mark C. 在接受的答案中发布的内容.

I ended up doing something similar to what Mark C. posted in the accepted answer.

推荐答案

如果您不想使用提供给您的 Clients.All API,您可以保留本地缓存连接的用户并将其用作您的连接用户列表.

If you're deadset on not using the Clients.All API that is given to you, you can keep a local cache of the connected users and use that as your list of connected users.

像这样:

static HashSet<string> CurrentConnections = new HashSet<string>();

    public override Task OnConnected()
    {
        var id = Context.ConnectionId;
        CurrentConnections.Add(id);

        return base.OnConnected();
    }

    public Task SendAllClientsMessage()
    {
        foreach (var activeConnection in GetAllActiveConnections())
        {
            Clients.Client(activeConnection).SendMessageAsync("Hi");
        }
    }

    public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled)
    {
        var connection = CurrentConnections.FirstOrDefault(x => x == Context.ConnectionId);

        if (connection != null)
        {
            CurrentConnections.Remove(connection);
        }

        return base.OnDisconnected(stopCalled);
    }


    //return list of all active connections
    public List<string> GetAllActiveConnections()
    {
        return CurrentConnections.ToList();
    }

这篇关于如何在 asp.net core SignalR 中迭代用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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