用Javascript实现WebSocket重新连接



var reconnectCounter = 0; 
var reconnectAttempts = Math.Infinity;
var socket;
var timeout;
var reconnectionDelayMax = 2000;
var reconnectionDelay = 1000;
function connect() {
  socket = new WebSocket('ws://localhost:9090');
  socket.onclose = function() {
    socket = null;
    // We only want to emit an error once.
    if(reconnectCounter === 0) {
      var error = new Error('WebSocket closed unexpectedly');
    }
    if(reconnectAttempts < reconnectCounter) {
      console.log('reconnect_failed', new Error('Reached maximum number of attempts'));
    } else {
      clearTimeout(timeout);
      var delay = reconnectCounter * reconnectionDelay;
      delay = Math.min(delay, reconnectionDelayMax);
      timeout = setTimeout(function () {
        reconnectCounter++;
        console.log('reconnecting', reconnectCounter);
        connect();
      }, delay);
    }
  };
  socket.onmessage = function() {
    console.log('we just received a message!');
  };
  socket.onopen = function() {
    reconnectCounter = 0;
    socket.send('test message');
  };
}
connect();

我正试图弄清楚为什么我会用上面的代码得到一个无限循环——这是在JSBin中http://jsbin.com/xefavu/1/edit

我不确定我是不是做错了什么?

  function connect(reconnecting) {
    clearTimeout(timeout);
    socket = = new WebSocket('ws://localhost:9090');
    socket.onmessage = function() {
      console.log('we just received a message');
    };
    socket.onopen = function() {
      reconnectCounter = 0;
      socket.send(JSON.stringify({token: token}));
    };
    socket.onclose = function() {
      socket = null;
      // We only want to emit an error once.
      if(reconnectCounter === 0) {
       console.error(new Error('WebSocket closed unexpectedly'));
      }
      if(reconnectAttempts < reconnectCounter) {
        console.log('reconnect_failed', new Error('Reached maximum number of attempts'));
      } else {
        var delay = reconnectCounter * reconnectionDelay;
        delay = Math.min(delay, reconnectionDelayMax);
        timeout = setTimeout(function () {
          reconnectCounter++;
          console.log('reconnecting', reconnectCounter);
          connect(true);
        }, delay);
      }
    };
  }
  connect();

虽然问题是服务器端不接受我的连接,但现在可以工作了。

相关内容

  • 没有找到相关文章

最新更新