0

我有以下 Sockjs 的重新连接方法,它几乎可以完全正常工作:

(function() {
  // Initialize the socket & handlers
  var connectToServer = function() {
    var warbleSocket = new SockJS('http://url.com:5555/warble');

    warbleSocket.onopen = function() {
      clearInterval(connectRetry);
      $('.connect-status')
        .removeClass('disconnected')
        .addClass('connected')
        .text('Connected');
    };

    warbleSocket.onmessage = function(e) {
      $('#warble-msg').text(e.data);
    };

    warbleSocket.onclose = function() {
      clearInterval(connectRetry);
      connectRetry = setInterval(connectToServer, 1000);
      $('.connect-status')
        .removeClass('connected')
        .addClass('disconnected')
        .text('Disconnected');
    };

    // Connect the text field to the socket
    $('.msg-sender').off('input').on('input', function() {
      warbleSocket.send($('.msg-sender input').val()); 
    });

    function send(a) {
        warbleSocket.send(a);    
    }

    return {
        send: send
    };
  }();
  var connectRetry = setInterval(connectToServer, 1000);
})();

我得到的错误是它试图重新连接时。错误是:

SyntaxError: missing ] after element list

在这一行:

connectRetry = setInterval(connectToServer, 1000);

有什么想法我在这里做错了吗?

4

2 回答 2

1

你的connectToServer变量不是一个函数,它是一个send具有函数属性的对象,所以说 . 是没有意义的setInterval(connectToServer, 1000)。试试这个:

setInterval(connectToServer.send, 1000);
于 2013-10-05T14:55:13.933 回答
0

你为什么不把事情简化一点?

我会把连接的东西放在一个特定的函数中,然后从 setInterval() 中调用它。

像这样的东西(小心使用,因为我没有测试这段代码,好吗?):

(function() {
  // Initialize the socket & handlers
  var connectToServer = function() {
    var warbleSocket;

    function connect() { 
      warbleSocket = new SockJS('http://url.com:5555/warble');

      warbleSocket.onopen = function() {
        // ...
      };

      warbleSocket.onmessage = function(e) {
        // ... 
      };

      warbleSocket.onclose = function() {
        // ...
    }

    // Connect the text field to the socket
    $('.msg-sender').off('input').on('input', function() {
      warbleSocket.send($('.msg-sender input').val()); 
    });

    function send(a) {
        warbleSocket.send(a);    
    }

    return {
        send: send
    };
  }();

  // you probably will need to call the first connection
  connectToServer();

  // and than set connection retry
  var connectRetry = setInterval(connectToServer.connect, 1000);
})();

我希望它对你有帮助。

问候,

海伦诺

于 2014-04-15T13:28:36.710 回答