首页 文章

SignalR中打开的连接列表?

提问于
浏览
9

如何从SignalR获取打开的连接列表而不发送“ping”或手动将它们注册到自己的列表中?

UPDATE: 或者只是为了获取从集线器发送消息的客户端数量 . 我想知道我应该等待多少响应(无需等待整个超时) .

(因为,当从集线器调用客户端时,SignalR不支持返回值,我通过客户端发送到集线器的另一条消息收集结果 . )

CLARIFICATION: 我假设SignalR必须知道哪些连接正在发送消息 .

2 回答

  • 1

    您可以将用户的ID存储在“已连接”上,并在断开连接时将其删除 . 请参阅 this is only an example 使用数据库来保留连接的ID

    protected Task OnConnected(IRequest request, string connectionId){
        var context=new dbContext();
        context.Connections.Add(connectionId);
        context.Save();
      }
      protected Task OnDisconnected(IRequest request, string connectionId){        
        var context=new dbContext();
        var id=context.Connections.FirstOrDefault(e=>e.connectionId==connectionId);
        context.Connections.Remove(id);
        context.Save();
      }
    

    然后,您需要访问连接ID列表的所有位置,请求您的数据库 .

  • 2

    我还没有找到任何直接的方法 .

    到目前为止我得到的最好的是遵循教程 - USERS BY CONNECTIONS IN SIGNALR ,您可以在链接中找到更多代码,我已将其简化为基本理解 .

    public void Register(HubClientPayload payload, string connectionId)
    {       
        lock (_lock)
        {
            List<String> connections;
            if (_registeredClients.TryGetValue(payload.UniqueID, out connections))
            {
                 if (!connections.Any(connection => connectionID == connection))
                 {
                     connections.Add(connectionId);
                 }
            }
            else
            {
                 _registeredClients[payload.UniqueID] = new List<string> { connectionId };
            }
        }        
    }
    

    public Task Disconnect(string connectionId)
    {       
        lock (_lock)
        {
             var connections = _registeredClients.FirstOrDefault(c => c.Value.Any(connection => connection == connectionId));     
             // if we are tracking a client with this connection remove it
             if (!CollectionUtil.IsNullOrEmpty(connections.Value))
             {
                connections.Value.Remove(connectionId);     
                // if there are no connections for the client, remove the client from the tracking dictionary
                if (CollectionUtil.IsNullOrEmpty(connections.Value))
                {
                    _registeredClients.Remove(connections.Key);
                }
             }                 
        return null;
    }
    

    也,

    public Task Reconnect(string connectionId)
    {
       Context.Clients[connectionId].reRegister();       
       return null;
    }
    

相关问题