Search code examples
angularasp.net-coreaspnetboilerplateasp.net-core-signalr

Auto reconnect SignalR client when server restart


I work with ASP.NET Core SignalR in the ASP.NET Boilerplate project and everything is ok while the server is up.

But for any reason that I need to restart the server, I see these errors:

enter image description here

And I have to refresh my web page to reconnect to SignalR.

Is there any way to check the server and reconnect without refreshing?

I use the default SignalR client that comes with the Angular template and ABP v4.0.1.


Solution

  • This has been fixed in v5.1.1 of the template: aspnetboilerplate/module-zero-core-template#498

    Reconnect loop

    yarn upgrade abp-web-resources@^4.1.0
    

    Reconnect loop was made available in [email protected]:

    // Reconnect loop
    function start() {
        connection.start().catch(function () {
            setTimeout(function () {
                start();
            }, 5000);
        });
    }
    
    // Reconnect if hub disconnects
    connection.onclose(function (e) {
        if (e) {
            abp.log.debug('Connection closed with error: ' + e);
        } else {
            abp.log.debug('Disconnected');
        }
    
        // if (!abp.signalr.autoConnect) {
        if (!abp.signalr.autoReconnect) {
            return;
        }
    
        // setTimeout(function () {
        //     connection.start();
        // }, 5000);
        start();
    });
    

    References:

    Reconnect loop + Circuit breaker

    yarn upgrade abp-web-resources@^5.1.1
    

    Circuit breaker was made available in [email protected]:

    // Reconnect loop
    function tryReconnect() {
        if (tries > abp.signalr.maxTries) {
            return;
        } else {
            connection.start()
                .then(() => {
                    reconnectTime = abp.signalr.reconnectTime;
                    tries = 1;
                    console.log('Reconnected to SignalR server!');
                }).catch(() => {
                    tries += 1;
                    reconnectTime *= 2;
                    setTimeout(() => tryReconnect(), reconnectTime);
                });
        }
    }
    
    // Reconnect if hub disconnects
    connection.onclose(function (e) {
        if (e) {
            abp.log.debug('Connection closed with error: ' + e);
        } else {
            abp.log.debug('Disconnected');
        }
    
        if (!abp.signalr.autoReconnect) {
            return;
        }
    
        // start();
        tryReconnect();
    });
    

    References: