7

I'm trying to detect when a SignalR Core connection is lost so that I can create a new one or at least warn the user.

connection.on('closed', data => {
    alert('Connection Closed');
});

This seems to have no effect. The messages stop arriving but this handler isn't fired.

On a related note, where is the documentation for event handling for the new version of this library?

Ian Warburton
  • 15,170
  • 23
  • 107
  • 189
  • 1
    Possible duplicate of [How to determine server disconnection from SignalR client?](https://stackoverflow.com/questions/9101053/how-to-determine-server-disconnection-from-signalr-client) – Sunny Patel Apr 16 '18 at 18:42
  • A Quick Google search led me to find this [MS Doc - Handling Connection Livetime Events](https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/handling-connection-lifetime-events) – Sunny Patel Apr 16 '18 at 18:43
  • But the new Core version has a different API. – Ian Warburton Apr 16 '18 at 18:44

2 Answers2

13

Use onclose:

connection.onclose(function (e) {
    alert('Connection Closed');
}

There's no documentation yet, but a handful of samples on GitHub.

aaron
  • 39,695
  • 6
  • 46
  • 102
0

Thank a lot aaron!!

I know it's old, but maybe it will help someone new to SignalR.

I found the documentation and some example to reconnect it

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();
Rene Rubio
  • 103
  • 1
  • 1
  • 8