Catch OnDisconnected event on client side with SignalR Core

Viewed 527

Is it possible to catch hub OnDisconnected event on javascript side with SignalR Core?

I need to do some actions on client side once OnDisconnected event is fired.

I tried to use onClose event by it didn't fire for instance in case I had updated the page or leave the page. But in this case OnDisconnected event on server side was fired.

2 Answers

Here is example code for client connection and event handling.

sdk: https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7/signalr.min.js

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chathub")
    .configureLogging(signalR.LogLevel.Information)
    .build();

async function start() {
    try {
        await connection.start();
        console.log("SignalR Connected.");
    } catch (err) {
        console.log(err);
        setTimeout(start, 5000);
    }
};

connection.onclose(async () => {
    await start();
});

// Start the connection.
start();

Referred from: https://docs.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0

In your SignalR Hub server side code, add override functions for the OnConnected and OnDisconnected events.

public override async Task OnConnectedAsync()
    {
         string name = Context.User.Identity.Name;

         _userConnections.Add(name, Context.ConnectionId);
         await Groups.AddToGroupAsync(Context.ConnectionId, name);
         _logger.LogInformation("Connecting to SignalRHub for User: {0} with connection {1}", name, Context.ConnectionId);
          
         await base.OnConnectedAsync();
    } 

public override async Task OnDisconnectedAsync(Exception ex){
    string name = Context.User.Identity.Name;
    _logger.LogWarning("Disconnecting to SignalRHub for User: {0}", name);

    var msg = "some message";
    await Clients.Groups(name).SendAsync("jsListener", msg);
                           
    await base.OnDisconnectedAsync(ex);           
}
Related