2

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?

Sam Joshua
3601 gold badge6 silver badges18 bronze badges
asked Jun 18, 2021 at 8:20

3 Answers 3

0

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.

answered Jun 18, 2021 at 8:26
Sign up to request clarification or add additional context in comments.

Comments

0

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']
 });
answered Jun 24, 2021 at 1:31

Comments

0

I recommend you use robust-websocket to handle disconnection events. You can set reconnection attempts based on the code of the CloseEvent.

answered Jun 30, 2021 at 3:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.