pladaria / reconnecting-websocket

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

Keep connection closed after close() #14

Closed PaulSD closed 7 years ago

PaulSD commented 7 years ago

If close() is called after handleClose() and before connect() (while the underlying WebSocket is closed), the WebSocket will be reopened again after the reconnectDelay timeout expires.

To prevent this, check shouldRetry after the reconnectDelay timeout expires to determine whether the WebSocket should be reopened.

My particular use case is: I would like to stop reconnecting if a particular WebSocket Close Status Code is received from the server. The obvious solution was:

var checkClose = function(event) {
  if(event.code == 4000) {
    rcws.removeEventListener('close', checkClose);
    rcws.close(event.code, undefined, {keepClosed: true, fastClose: true});
  }
};
rcws.addEventListener('close', checkClose);

However, this doesn't work as expected because handleClose() is called before my checkClose() function and there is no way for me to cancel the reconnectDelay timer to prevent ReconnectingWebsocket from reconnecting after I call rcws.close(). This commit fixes this issue.

pladaria commented 7 years ago

Thank you! Good catch. Will add test coverage and release a new npm version

pladaria commented 7 years ago

published reconnecting-websocket@3.0.5

msageryd commented 7 years ago

Thank you @PaulSD for your solution and contribution. This was exactly what I needed to kick out users with expired tokens.

Also, big thumbs up for @pladaria for a great library. I've tried out a bunch of libraries for React Native. This is by far my favourite.