【问题标题】:List of opened connections in SignalR?SignalR中打开的连接列表?
【发布时间】:2015-07-14 07:17:13
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我不认为你可以。

标签: c# .net signalr signalr-hub


【解决方案1】:

您可以在连接时存储用户 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 列表的任何地方,您都可以请求您的数据库。

【讨论】:

  • 你还需要重新连接
【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    相关资源
    最近更新 更多