在Javascript中实现WebSocket重新连接

时间:2014-09-17 01:41:28

标签: 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

我不确定我做错了什么?

1 个答案:

答案 0 :(得分:0)

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

现在可以使用,但问题是服务器端不接受我的连接。