Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disable reconnect programmatically #42

Closed
Symous opened this issue Jan 12, 2019 · 15 comments
Closed

Disable reconnect programmatically #42

Symous opened this issue Jan 12, 2019 · 15 comments
Labels

Comments

@Symous
Copy link

Symous commented Jan 12, 2019

Hi, awesome lib.
Is there any way that we can disable reconnect programmatically ?

For example, we init a sockette instance with maxAttempts by default(always enable recconnecting), after a several times of connection failure, I would like to provide a way to disable the further reconnecting manually. Thanks.

@lukeed
Copy link
Owner

lukeed commented Jan 12, 2019

Hey, thanks!

Not sure I understand the question. Are you already using maxAttempts or no?

@Symous
Copy link
Author

Symous commented Jan 12, 2019

@lukeed hi, friend. I didnt set maxAttempts, imagine that when the socket is failed to connect for many times and continue reconnecting. is there a method such as socket.stopReconnect() to cancel automatically reconnect?

@lukeed
Copy link
Owner

lukeed commented Jan 12, 2019

Hey,

Unfortunately no, this is what maxAttempts is for. If you don't set it, then Infinity is used as default which will make Sockette attempt to reconnect forever

You definitely need to set this option. Your only other attempt is to call .close() but that may result in an error since you don't have an open connection.

@Symous
Copy link
Author

Symous commented Jan 12, 2019

@lukeed, no, i need the reconnect feature, but I want control whether continue reconnecting during the reconnecting ...

@Symous
Copy link
Author

Symous commented Jan 14, 2019

@lukeed, for example we configure sockette { maxAttempts : 100} , when it is trying reconnecting for the 10th time and still failed, I guess that the websocket host may can not be reached and I don't want to continue reconnecting, so I'd like to call a method such as sockette.stopReconneting() to stop trying the next 90 times of reconnecting.

@lukeed
Copy link
Owner

lukeed commented Jan 14, 2019

Then maxAttempts should be 10

@Symous
Copy link
Author

Symous commented Jan 14, 2019

@lukeed thank you but this is just a example , "10" is a dynamically number which depend on the operator who may stop reconnecting after 20/50/80th time of failure.

@Symous
Copy link
Author

Symous commented Jan 14, 2019

just like we give the operator a dialog that remind of reconnecting every time. the operator may click a button named "don't reconnecting again" to invoke sockette.stopReconnecting();

@lukeed
Copy link
Owner

lukeed commented Jan 14, 2019

Sorry, don't think I've been clear in what I'm trying to illustrate to you. So here's some code instead:

let ws;
let wsConfig = {
  maxAttempts: 10,
  onopen(ev) {
    console.log('Connected!')
  },
  onmessage(ev) {
    console.log('Received:', ev);
  },
  onreconnect(ev) {
    console.log('Reconnecting...');
  },
  onmaximum(ev) {
    console.log('Reached max!');

    // Display prompt to continue
    //   or restart programmatically.
    if (window.confirm('Continue reconnecting?')) { 
      // Increment max by X
      wsConfig.maxAttempts += Math.floor(Math.random() * 20);

      // Reinitialize Sockette with same config
      //   except for increased `maxAttempts` limit
      init();
    }
  }
};

function init() {
  ws = new Sockette('ws://localhost:3000', wsConfig);
}

init();

@Symous
Copy link
Author

Symous commented Jan 14, 2019

@lukeed please check this thanks.

let ws;
let errorTimes = 0;
let wsConfig = {
  maxAttempts: 10000,
  onopen(ev) {
    console.log('Connected!')
  },
  onmessage(ev) {
    console.log('Received:', ev);
  },
  onerror(ev) {
      errorTimes ++ ;
      // ask user whether continue every 10 times of reconnecting failure
      if(errorTimes % 10 == 0){
          if(window.confirm(`you have failed to connect for the ${errorTimes} times, whether stop reconnecting ?`)){
            // a fake method that diabled next reconnecting
            ws.stopReconnecting();
          }
      }
  },
  onreconnect(ev) {
    console.log('Reconnecting...');
  },
  onmaximum(ev) {
    console.log('Reached max!');  
  }
};

function init() {
  ws = new Sockette('ws://localhost:3000', wsConfig);
}

init();

@lukeed
Copy link
Owner

lukeed commented Jan 14, 2019

Gotcha. This will work (tested):

let tries = 0;
let ctx = sockette('ws://localhost:3000', {
  onopen(ev) {
    // Mutate the WebSocket, but save
    //   a reference to Sockette's "onclose"
    let old = ev.target.onclose;
    ev.target.onclose = e => {
      e.abort ? console.log('✔ Stopped') : old(e);
    };
  },
  onreconnect(ev) {
    // This always runs
    console.log('attempting...', ev.target);
    // This is your confirm/prompt or whatever
    if (++tries % 3 === 0) {
      console.warn('~> manually aborting');
      // Sending a custom "abort" key to stop 
      //   reconnect via Sockette's "onclose" (saved above)
      ev.target.onclose({ abort:true });
    }
  },
  onclose(ev) {
    // This will always run when `old(e)` is called
    console.log('My custom onclose callback:', ev.code);
  }
});

@Symous
Copy link
Author

Symous commented Jan 14, 2019

@lukeed, sorry for such many questions... :( I can not understand... if there we can provide a method to force to stop the reconnecting at any times?

@lukeed
Copy link
Owner

lukeed commented Jan 14, 2019

Not a problem! No sorry, your use case is specific and I don't think it belongs in the core of Sockette. It can be easily done, as shown above.

What part don't you understand about the snippet?

It counts how many times it's tried to reconnect (thru tries, just like your errors). My example is doing every 3 attempts, but you can change that back to 10, as well as reincluding the window.confirm prompt

Either way, the important part is that yoiu override the onclose method on the WebSocket directly (ev.target). You do this so that you decide if the reconnect should happen or not. However, you must save a reference to the old onclose because that's how Sockette will decide if it wants to reconnect or not: https://github.com/lukeed/sockette/blob/master/src/index.js#L19

I am using the abort key as a way to signal to myself to prevent reconnecting. You can call this whatever you want, it just has to match your onclose override.

The only real difference is between your snippet and mine is that mine uses the onclose instead of your onerror... This is because onclose is what triggers reconnection 99% of the time (thru link above).

@Symous
Copy link
Author

Symous commented Jan 15, 2019

@lukeed thanks my friend, I have achieve this by overiding onclose. :)

@Symous Symous closed this as completed Jan 15, 2019
@lukeed
Copy link
Owner

lukeed commented Jan 15, 2019

Awesome! Lemme know if you have any further questions about the snippet. I had it working in a demo script, which is where I copied it from

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants