我为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);
任何想法我在这里做错了什么?
答案 0 :(得分:1)
您的connectToServer
变量不是函数,它是具有属性send
的对象,它是一个函数,所以说setInterval(connectToServer, 1000)
没有意义。试试这个:
setInterval(connectToServer.send, 1000);
答案 1 :(得分: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);
})();
我希望它可以帮到你。
此致
Heleno的