'Awaiting localhost to reload in ASP.NET Core

I have an ASP.NET Core server, which is using SignalR to generate HTML pages dynamically at runtime through JavaScript. After i shut my application down, in the console i can read that SignalR is disconnected:

signalr.js:2404 Error: Connection disconnected with error 'Error: Websocket closed with status code: 1006 ()'.

The question is - what do i need to do to setup SignalR to wait incoming connection again after disconnecting? Meaning that when my application will be up again, preloaded localhost page will connect automatically and continue working with the new instance of my app.

The way i initialize SignalR in JS:

var connection = new signalR.HubConnectionBuilder()
    .withUrl("/foo")
    .build();

And then

connection.on("state", function (state) {
    // some business logics there
});

connection.start().catch(function err() {
    return console.error(err.ToString());
});


Solution 1:[1]

Brando's answer lead me to do the following thing:

var connection = new signalR.HubConnectionBuilder()
    .withUrl("/foo")
    .build();

function start() {
    connection.start().catch(function () {
        setTimeout(function () {
            start();
            //there we can process any HTML changes like
            //disabling our loader etc. start() will fail
            //with exception if there's no server started
            //and it will try again in 5 seconds
        }, 5000);
    });
}

connection.onclose(e => {
    //process here any HTML changes like
    //showing the loader, etc, an then
    start();
})

connection.on("foo", function (state) {
    // some business logics there
});

start();

It looks like typical relationship between ASP.NET and signalR + vanilla javascript

Solution 2:[2]

As far as I know, Signalr Client library provide the auto reconnect feature. You could enable it by using the withAutomaticReconnect. Please notice: Without any parameters, WithAutomaticReconnect configures the client to wait 0, 2, 10, and 30 seconds respectively before trying each reconnect attempt. After four failed attempts, it stops trying to reconnect.

Also you could write codes to do Manually reconnect. More details, you could refer to this article.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Brando Zhang