pladaria / reconnecting-websocket

Reconnecting WebSocket. For Web, React Native, cli (Node.js)
MIT License
1.22k stars 197 forks source link

clearTimeout in close event. #50

Closed chbdetta closed 6 years ago

chbdetta commented 6 years ago

Not stoping the connectingTImeout counter on close event will sometime close the wrong websocket.

         ws = new (<any>config.constructor)(wsUrl, protocols);

         connectingTimeout = setTimeout(() => {
             log('timeout');
             ws.close();        // in some situation, ws is a connected websocket.
             emitError('ETIMEDOUT', 'Connection timeout');
         }, config.connectionTimeout);

Some routine like this will happen:

  1. connectionTimeout = 4000, maxRetries = 10, reconnectDelay = 1000
  2. start connect().
  3. assign connectingTimeout as connectingTimeout#1.
  4. websocket connection fails, => handleClose.
  5. 1000ms later, reconnect, start connect() again.
  6. assign connectingTimeout as connectingTimeout#2.
  7. connect success, handle open event.
  8. clearTimeout(connectingTimeout#2) <=== note that connectingTimeout#2 is cleared but connectingTimeout#1 is not!
  9. 4000ms later, connectingTimeout#1 calls, ws.close() <==== This will close the connected websocket
  10. reconnection ...

I stop the connectingTimeout in close event, so that it won't close connected ws.

coveralls commented 6 years ago

Coverage Status

Coverage increased (+0.02%) to 98.485% when pulling 302bcb694f41c21a55e967399a92d3a4689e27e3 on chbdetta:master into 31a0f01af4c96dfb1ba0c17b1124de204cd0e513 on pladaria:master.

pladaria commented 6 years ago

Hi, thanks for contributing.

I've just released a full rewrite of this library and this case should be covered. There are lots of breaking changes, please have a look at the readme.

Regards