I don't have that much experience with WebSockets yet so I wanted to ask a more general question about what is the best way to maintain a stable connection.
Basically, I use a WebSocket client in my application to connect to a remote server that will kill idle connections after some time of inactivity (I think 1 hour or so). To keep the connection alive, I started implementing the onerror and onclose handler functions for the WebSocket to reconnect if that happens. That works great for certain errors, but I noticed that sometimes after a long period of inactivity it seems like the connection is still open and I am able to send messages to the socket but I don't receive a response from the server for like 2 minutes until the onclose handler of the socket I implemented fires and replaces the socket.
However, this is much too late for my use cases. What's the best way to deal with it? Is it good practice to periodically close and replace the connection on my end to ensure a working socket connection is always open? E.g. by setting an interval to call .close() on the WebSocket? Anyone experienced something similar?
3 Answers 3
I found that this package https://github.com/pladaria/reconnecting-websocket can solve the reconnection issues for Websocket connections. And it has a list of configurable options, one of them is reconnectionDelayGrowFactor which determines how fast the reconnection delay grows.
Comments
with socket.io there are parameters you can pass in on the client side that handle socket connections and timeouts etc. I can't imagine socket.io is the only websocket to provide this configurability. I'm sure they all do.
this.socket = openSocket('https://yoururl', {
'force new connection': true,
'reconnectionAttempts': 'Infinity',
'timeout': 10000,
transports: ['websocket']
});
Comments
I recommend you use robust-websocket to handle disconnection events. You can set reconnection attempts based on the code of the CloseEvent.
Comments
Explore related questions
See similar questions with these tags.