Search code examples
javascriptc#asp.net-coresignalr

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

  • 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