0
votes

I'm using the dotnet client and Asp.Net core SignalR v. 3.1

I want to be able to detect (server-side) when a user lost connection and is currently attempting to reconnect or just lost connection due to an error.

Unfortunately the OnDisconnectedAsync function is only called when the user has disconnected and not while he is reconnecting.

How could I do this?

1

1 Answers

0
votes

I want to be able to detect (server-side) when a user lost connection and is currently attempting to reconnect or just lost connection due to an error.

As far as I know, at present Asp.net core SignalR doesn't have the build-in method to check whether the client is connected or not, or if there any clients exist in the group. And from the official document, we could also find that:

Group membership isn't preserved when a connection reconnects. The connection needs to rejoin the group when it's re-established. It's not possible to count the members of a group, since this information is not available if the application is scaled to multiple servers.

To check whether the group contains any connected clients, as a workaround, in the hub method, you could define a global variable to store the group name and the online count, or you could store the user information (username, group name, online status etc.) in the database.

In the OnConnectedAsync method, you could add the user to the group and calculate the online count or change the user's online status, in the OnDisconnectedAsync method, remove users from the group and change the online user count. Create a custom method to check/get the count of online user.

Code like this:

public class ChatHub : Hub
{
    private readonly ApplicationDbContext _context;

    public ChatHub(ApplicationDbContext context)
    {
        _context = context;
    }
    public override Task OnConnectedAsync()
    {
        //add user to group 
        //store the group information into database or global variable.               
        return base.OnConnectedAsync();
    }
    public async Task SendMessage(string user, string message)
    { 
        
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
     
    //send message to group
    public async Task SendMessageToGroup(string sender, string receiver, string message)
    {

        await Clients.Group(receiver).SendAsync("ReceiveMessage", sender, message);
    }

    //Create a custom method: query the group table and get the count of online user.
    public async Task GetOnlineCount(string groupname)
    { 
         
    }

    public override async Task OnDisconnectedAsync(Exception exception)
    {
        //remove user from group 
        //update the group table
        await base.OnDisconnectedAsync(exception);
    }
}