SignalR中已打开的连接列表?

时间:2015-07-14 07:17:13

标签: c# .net signalr signalr-hub

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

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

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

澄清:我认为SignalR必须知道哪些连接正在发送消息。

2 个答案:

答案 0 :(得分:2)

您可以将用户的ID存储在“已连接”上,并在断开连接时将其删除。请参阅这只是一个示例,使用数据库来保存连接的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的列表,请求您的数据库。

答案 1 :(得分:1)

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

我到目前为止所做的最好的是遵循教程 - 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;
}