当该用户断开连接时,signaler中有没有办法将其从列表中删除?

时间:2019-02-13 14:16:45

标签: c# asp.net-core signalr

我正在用Signalr制作一个小型聊天应用程序,当用户单击“加入”时,服务器将该用户添加到ConnectedUsers列表中。

但是我应该如何从列表中删除特定用户,并通知其他客户端该用户已断开连接?

ChatHub.cs

static List<User> ConnectedUsers = new List<User>();

public async Task Join(string name) {

            var id = Context.ConnectionId;
            ConnectedUsers.Add(new User {ID = id, Name = name});
            await Clients.Caller.SendAsync("update", "You have connected to the server.");
            await Clients.Others.SendAsync("update", name + " has joined the server.");
            await Clients.All.SendAsync("update-people", JsonConvert.SerializeObject(ConnectedUsers));
        }

public override async Task OnDisconnectedAsync(Exception exception)
        {
            var _user = ConnectedUsers[Convert.ToInt32(Context.ConnectionId)];
            await Clients.All.SendAsync("test", _user);
            //ConnectedUsers.Remove();
            return base.OnDisconnectedAsync(exception);
        }

User.cs

public class User
    {
        public string ID { get; set; }
        public string Name { get; set; }
    }

我希望用户从ConnectedUsers列表中删除,并通知其他客户端有关用户断开连接的信息,但是我无法在OnDisconnectedAsync的替代中使用await SendAsync。

1 个答案:

答案 0 :(得分:2)

OnDisconnectedAsync函数中,在ConnectedUsers中找到断开连接的用户(您有ConnectionId,之前已将其分配给用户ID),然后从列表中删除该对象。之后,广播广播更新了用户列表。

示例:

public override Task OnDisconnectedAsync(Exception exception)
    {
        var itemToRemove = ConnectedUsers.Single(r => r.ID == Context.ConnectionId);
        ConnectedUsers.Remove(itemToRemove);

        Clients.Others.SendAsync("update", itemToRemove.Name + " has left the server.");
        Clients.All.SendAsync("update-people", JsonConvert.SerializeObject(ConnectedUsers));
        return base.OnDisconnectedAsync(exception);
    }