Reputation: 15039
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?
Upvotes: 1
Views: 1974
Reputation: 1479
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:
this.connection = new HubConnectionBuilder()
.withUrl(`${environment.apiUrl}/hubRoute`)
.configureLogging(LogLevel.Warning)
.build();
filter(() => this.hubService.connection.state === HubConnectionState.Disconnected)
// safe to call hubService.connection.start();
Hope that helps someone else stumbling upon the same thing!
Upvotes: 2