dotnet / dotnet/AspNetCore.Docs
Retry Connection logic for SignalR
- Dominant language
- C#
- Stars
- 13.1k
- Forks
- 24.6k
- Avg merge
- 1d 3h
- Merged PRs (30d)
- 97
Description
( See Brennan's comment in discussion below for the suggestion related to docs. )
### Is there an existing issue for this?
- [X] I have searched the existing issues
### Describe the bug
Some browser tab will go into sleep if it is not active (ex: google chrome). In that case how can we ensure the connection with signalR automatically when the browser tab is get back to active.
We are looking for a way to make the signalR connection to be established all the time inorder to show the live updates in our react application.
The below is the signalr intialization and reconnection logic that we have adpoted:
```
const useSignalRInitialization = (): HookReturnTypes => {
const getNewAccessTokenAPI = useGetSignalRAccessToken()
const signalRConnection = new HubConnectionBuilder()
.withUrl(getSignalRConnectionUrl() , {
accessTokenFactory: () => getSignalRAccessToken() ,
skipNegotiation: true,
transport: HttpTransportType.WebSockets
})
.configureLogging(LogLevel.Information)
.build()
const isTokenExpired = () => {
return new Date().getTime() > new Date().getTime()
}
const refreshAccessToken = async (): Promise => {
if (isTokenExpired()) {
await getNewAccessTokenAPI.triggerAPI({
deviceId: getDeviceId()
})
startConnection()
}
}
const startConnection = async (): Promise => {
if (signalRConnection.state === HubConnectionState.Disconnected) {
try {
await signalRConnection.start()
console.log('Connected to SignalR')
} catch (err) {
console.error('Error connecting to SignalR:', err)
refreshAccessToken()
}
}
}
useEffect(() => {
startConnection()
signalRConnection.onclose(async () => {
console.log('trying to reconnect to signalR server')
refreshAccessToken()
})
return () => {
clearInterval(interval)
signalRConnection.stop()
}
}, [])
return {
signalRHubConnection: signalRConnection
}
}
```
### Expected Behavior
Any suggestions or improvements in the reconnection logic of the signalR to ensure the connection should be established all the time. And also provide us some insights to tackle the below case:
Some browser tab will go into sleep if it is not active (ex: google chrome). In that case how can we ensure the connection with signalR automatically when the browser tab is get back to active.
### Steps To Reproduce
_No response_
### Exceptions (if any)
_No response_
### .NET Version
_No response_
### Anything else?
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.