Giter Club home page Giter Club logo

Comments (15)

lukeed avatar lukeed commented on July 20, 2024

Hey, thanks!

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

from sockette.

Symous avatar Symous commented on July 20, 2024

@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?

from sockette.

lukeed avatar lukeed commented on July 20, 2024

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.

from sockette.

Symous avatar Symous commented on July 20, 2024

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

from sockette.

Symous avatar Symous commented on July 20, 2024

@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.

from sockette.

lukeed avatar lukeed commented on July 20, 2024

Then maxAttempts should be 10

from sockette.

Symous avatar Symous commented on July 20, 2024

@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.

from sockette.

Symous avatar Symous commented on July 20, 2024

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();

from sockette.

lukeed avatar lukeed commented on July 20, 2024

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();

from sockette.

Symous avatar Symous commented on July 20, 2024

@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();

from sockette.

lukeed avatar lukeed commented on July 20, 2024

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);
  }
});

from sockette.

Symous avatar Symous commented on July 20, 2024

@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?

from sockette.

lukeed avatar lukeed commented on July 20, 2024

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).

from sockette.

Symous avatar Symous commented on July 20, 2024

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

from sockette.

lukeed avatar lukeed commented on July 20, 2024

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

from sockette.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.