Reputation: 21368
Working with .net Core and have setup everything using this tutorial: https://learn.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-3.1&tabs=visual-studio.
I wanted to be able to use lifetime events based on this tutorial: https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client
However I get:
connection.stateChanged or connection.disconnected is not a function
var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
connection.start().then(function () {
}).catch(function (err) {
return console.error(err.toString());
});
connection.stateChanged(function () {
console.log('in');
});
I would like to detect "disconnected" even on the client.
Upvotes: 1
Views: 6056
Reputation: 2268
To monitor the connection being dropped, I've not had a lot of luck with the onclose method. I assume this is when the server side actually intentionally closes the connection to the client in a controlled manner, rather than the connection dropping.
Instead I use the onreconnecting method along with the withAutomaticReconnect configuration.
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('https://localhost:7142/jobshub')
.withAutomaticReconnect({
nextRetryDelayInMilliseconds: _ => {
return 3000;
}})
.build();
...
this.hubConnection.onreconnecting((e) => {
this.connectedToServer = false;
console.log('signalr connection dropped - reconnecting');
});
If the hub connection is reconnecting then I know the connection must have dropped and I can respond.
I also handle the reconnected event, so I can then restore functionality back to my app
this.hubConnection.onreconnected(() => {
this.connectedToServer = true;
console.log(`signalr connection restored`);
});
Upvotes: 0
Reputation: 12725
From the MS Doc on HubConnectionState
, there are only 2 states:
Those states are exposed through a state property in the connection but there are no states for anything else.
From the what anurse said in this github issue , thestart
Promise lets you know when the connection starts and the closed
event lets you know it's stopped. They don't have automatic reconnects, so those are the only state transitions.
So you could use the following method as Dennis1679 said above
connection.onclose(function(){
console.log('connecition closed');
});
Upvotes: 2