Detect lost connection from SignalR Core connection
Asked Answered
C

2

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?

Came answered 16/4, 2018 at 18:39 Comment(3)
Possible duplicate of How to determine server disconnection from SignalR client?Lib
A Quick Google search led me to find this MS Doc - Handling Connection Livetime EventsLib
But the new Core version has a different API.Came
A
13

Use onclose:

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

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

Acetylide answered 17/4, 2018 at 1:56 Comment(2)
When does it fire? If I shut down my web server, the page seems none the wiser.Came
Ian Warburton, it seems to take awhile, but it does occur. I'm trying to figure this out too.Jag
E
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();
Ermina answered 14/9, 2022 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.