WebSocket onclose只调用一次

时间:2016-01-17 13:52:57

标签: javascript websocket

我正在编辑一个网站的javascript,我希望我的脚本在与WebSocket的连接丢失时重新连接。

var reconnect = 0;
WS.onclose = function(event){
bot_debug("Connection has been lost, reconnecting...",0); WS = null;setTimeout(connect,1000);console.log("reconnecting");reconnect++;
};

WS是websocket的变量。代码只工作一次 - 当服务器断开连接时,脚本按预期工作(重新连接),但如果连接再次丢失,则此代码根本不起作用。可能是什么原因?

connect()函数(它的网站功能,不是我的):

function connect() {
  if (!WS) {
    chat('italic', 'Generating authentication token...');
    $.ajax({
      url: '/scripts/getToken.php',
      success: function (data) {
        if (data) {
          if (data == 'nologin') {
            chat('italic', 'Please sign in through Steam to connect.');
          } else if (data == 'max') {
            chat('italic', 'CSGODouble servers are currently full - please try back later.');
          } else {
            chat('italic', 'Connecting to server...');
            WS = new WebSocket(HOST + '/' + data);
            WS.onopen = function () {
              chat('italic', 'Connected!');
            };
            WS.onerror = function (event) {
              chat('italic', 'Error: Connected closed.');
            };
            WS.onclose = function (event) {
              WS = null;
              chat('italic', 'Connection lost...');
            };
            WS.onmessage = onMessage;
          }
        } else {
          chat('italic', 'Error: Failed to get AT');
        }
      },
      error: function (err) {
        chat('italic', 'Error: Failed to get AT');
      }
    });
  } else {
    console.log('Error: Existing connection found');
  }
}

0 个答案:

没有答案