如何从Hub中删除用户?

时间:2017-02-16 12:18:28

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

我通过ajax post请求向控制器中的方法发送一个字符串' userName'我应该踢 是否可以从调用控制器中的方法的当前集线器中删除用户?

  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});
    }

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

1 个答案:

答案 0 :(得分:2)

服务器端 -

您应该在连接时存储用户的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();

希望你有答案