I have a react native app that uses an AWS server, written in Python, that is connected via WebSockets.
When users navigate away from the app for a time greater than ~30 seconds, they disconnect from the server and the WebSocket closes.
This prevents our users from being able to do anything within the app, as the WebSocket closing prevents the front end of the app from communicating to the server.
I've tried to perform a "CPR" on the WebSocket so that when it disconnects, it reconnects to the server.
Below is my code on the front end that attempts to reconnect the app:
global.number_of_attempts = 20
function restore_attempts(){
if (client_instance.websocket.is_connected){
global.number_of_attempts = 20 // reset on success
console.log(number_of_attempts, 'number of attempts is here')
}
}
function websocketCPR() {
client_instance = new UserClient(DEFAULT_SETTINGS)
client_instance.connect() //this allows it to connect to ws
setTimeout(restore_attempts, 10000) // reset on success
client_instance.websocket.onclose = function(evt) {
console.log("THE WEBSOCKET IS NOW _CLOSED__")
global.number_of_attempts = global.number_of_attempts - 1
console.log(global.number_of_attempts, 'it is attempted')
if (global.number_of_attempts > 0){
client_instance = null
setTimeout(websocketCPR, 500)
}
}
}
client_instance.websocket.onclose = function(evt) {
console.log("THE WEBSOCKET IS NOW _CLOSED__")
global.number_of_attempts = global.number_of_attempts - 1
console.log(global.number_of_attempts, 'it is attempted')
if (global.number_of_attempts > 0){
client_instance = null
setTimeout(websocketCPR, 500)
}
}