BlueDragon709
BlueDragon709

Reputation: 316

Is there a way in signalr to remove a user from a list when that user disconnects?

I am making a little chat app with signalr, and when users click on Join the server adds that user to the ConnectedUsers list.

But how am i supposed to remove a specific user from the list and notify the other clients that the user disconnected?

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

I expect that the user gets removed from the ConnectedUsers list and notify the other clients about the user disconnecting, but I can't use a await SendAsync in the override for OnDisconnectedAsync.

Upvotes: 2

Views: 1768

Answers (1)

Srdjan
Srdjan

Reputation: 582

In OnDisconnectedAsync function, find disconnected user in your ConnectedUsers (you have ConnectionId which earlier you assigned to the User ID) and remove that object from the list. After that boradcast updated users list.

Example:

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

Upvotes: 3

Related Questions