【问题标题】:How can I remove user from Hub?如何从 Hub 中删除用户?
【发布时间】:2017-02-16 12:18:27
【问题描述】:

我正在通过 ajax 发布请求向控制器中的方法发送一个我应该踢的字符串“用户名”。 是否可以从当前集线器中删除用户调用控制器中的方法?

  public ActionResult Kick(string userName)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
        var user = userService.GetUserByName(userName);
        var room = chatRoomService.GetRoomById(user.ChatRoomId.Value);
        user.IsKicked = true;
        userService.LeaveRoom(user);
        hubContext.Groups.Remove(user.ConnectionIdInHub, room.Name);
        return Json(new {success = true});
    }

我可以在这个方法的某个地方断开用户与集线器的连接吗?

【问题讨论】:

  • 用户被踢了应该怎么办?根据您的架构,用户始终连接到集线器。
  • 如果我以某种方式为他关闭集线器中的连接,他将不会再收到来自活跃用户的消息
  • @Toni 他在聊天室中时已连接到集线器。当他离开房间时,signalR 方法断开他的连接

标签: javascript c# ajax asp.net-mvc signalr


【解决方案1】:

服务器端-

您应该在用户连接时存储用户的connection ID

在服务器端这样-

public override Task OnConnected()
{
    Boolean isFoundAnydevice = false;

    if(receivedClientId.Length>0)   //With Param
    {
        int noOfSelectedDevice = _context.TargatedDevice.Where(x => x.PhoneId == receivedClientId).Count();
        if (noOfSelectedDevice > 0)
            isFoundAnydevice = true;
    }
    else   //With no Param
    {
        String deviceId = _context.Device.Where(d => d.ConnectionId == this.Context.ConnectionId).Select(d => d.ClientId).SingleOrDefault();
    int noOfSelectedDevice = _context.TargatedDevice.Where(x => x.PhoneId == deviceId).Count();
        if (noOfSelectedDevice > 0)
            isFoundAnydevice = true;
    }

    if (isFoundAnydevice)
    {
        _logger.LogWarning(
                        receivedClientId + " added to Test group"
                        );
        Groups.Add(this.Context.ConnectionId, testGroupName);
    }   

    return base.OnConnected();
}

然后你可以很容易地从DB中找到用户的连接ID。

现在您可以像这样轻松停止集线器连接-

public Task Disconnect(string connectionId)
{
    try
    {
        lock (_lock)
        {
            var connections = _registeredClients.Where(c => c.Value.Any(connection => connection == connectionId)).FirstOrDefault();

            // 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);
                }
            }
        }
    }
    catch (Exception ex)
    {
        Log.Error(this, "Error on disconnect in hub", ex);
    }

    return null;
}

可以在这里找到更多。

客户端-

如果你喜欢从客户端做,你可以这样做-

$.connection.hub.stop();

希望你有答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 2014-07-04
    • 1970-01-01
    • 2021-11-30
    • 2019-04-03
    • 2017-10-27
    • 2023-03-03
    相关资源
    最近更新 更多