SignalR how to avoid connecting twice

1.7k Views Asked by At

In my application once I logged in I redirect to Home page where I have the following script:

// Defining a connection to the server hub.
        var myHub = $.connection.myHub;
        // Setting logging to true so that we can see whats happening in the browser console log. [OPTIONAL]
        $.connection.hub.logging = true;
        // Start the hub
        $.connection.hub.start();

        myHub.client.newMessageReceived = function (message) {
            alert(message);
        }

In my Hub.cs server I have:

public override Task OnConnected()
        {
            var connectionId = Context.ConnectionId;

            // here do other stuff...

            return base.OnConnected();
        }

The first time I get into the Home page I can see that I get a connectionId but If I reload again the page I get a different one and that's happening because the jquery script it's being called again.

How can I detect in my client if Im already connected so I dont start() the hub everytime I refresh that page?

1

There are 1 best solutions below

0
On BEST ANSWER

I had a similar scenario where a redirect was kicking off another request to connect to SignalR - I solved by checking the connection.state and filtering out requests unless the connection was in a Disconnected state. I was using angular + rxjs, but hopefully similar principles still apply:

In the hub service

this.connection = new HubConnectionBuilder()
      .withUrl(`${environment.apiUrl}/hubRoute`)
      .configureLogging(LogLevel.Warning)
      .build();

And then in the request to connect to SignalR

filter(() => this.hubService.connection.state === HubConnectionState.Disconnected)
// safe to call hubService.connection.start();

Hope that helps someone else stumbling upon the same thing!