信号 r 存储 Context.connectionID

signal r storing the Context.connectionID

我是 signalr 的新手,我想为特定客户端生成连接 ID 并将其存储在数据库中,一旦任何客户端完成任何更新都会通知所有人,但是存储 [=13 是一种好习惯吗=] 到数据库,如果不是我想知道维护所有客户端之间的连接需要帮助。

当客户端调用服务器端的函数时,您可以通过 Context.ConnectionId 检索它们的连接 ID。现在,如果您想通过集线器外部的机制访问该连接 ID,您可以:

只需让 Hub 调用传入连接 ID 的外部方法即可。 通过添加到 OnConnected 中的字典并从 OnDisconnected 中删除来管理连接的客户端列表,如 public static ConcurrentDictionary<string, MyUserType>...。获得用户列表后,您就可以通过外部机制查询它。

Ex 1:

    public class MyHub : Hub
    {
        public void AHubMethod(string message)
        {
            // Send the current clients connection id to your external service
            MyExternalSingleton.InvokeAMethod(Context.ConnectionId); 
        }
    }
EX : 2

    public class MyHub : Hub
{
    public static ConcurrentDictionary<string, MyUserType> MyUsers = new ConcurrentDictionary<string, MyUserType>();

    public override Task OnConnected()
    {
        MyUsers.TryAdd(Context.ConnectionId, new MyUserType() { ConnectionId = Context.ConnectionId });
        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        MyUserType garbage;

        MyUsers.TryRemove(Context.ConnectionId, out garbage);

        return base.OnDisconnected();
    }

    public void PushData(){
        //Values is copy-on-read but Clients.Clients expects IList, hence ToList()
        Clients.Clients(MyUsers.Keys.ToList()).ClientBoundEvent(data);
    }
}

public class MyUserType
{
    public string ConnectionId { get; set; }
    // Can have whatever you want here
}

// Your external procedure then has access to all users via MyHub.MyUsers