我正在尝试找出一种方法,让我的 SockJS 客户端在服务器出现故障时重新连接到服务器。
我目前有这个:
new_conn = function() {
socket = new SockJS(protocol + serverDomain + '/echo', null, {
'protocols_whitelist': ['websocket', 'xdr-streaming', 'xhr-streaming', 'iframe-eventsource', 'iframe-htmlfile', 'xdr-polling', 'xhr-polling', 'iframe-xhr-polling', 'jsonp-polling']
});
};
socket.onopen = function () {
clearInterval(recInterval);
};
socket.onclose = function () {
recInterval = window.setInterval(function () {
new_conn();
}, 2000);
};
问题是即使在成功重新连接后 setInterval
仍会触发。似乎 socket.onopen
永远不会被执行。
知道我可能做错了什么吗?
最佳答案
我认为这可能与变量作用域有关。试试这个:
var recInterval = null;
new_conn = function() {
socket = new SockJS(protocol + serverDomain + '/echo', null, {
'protocols_whitelist': ['websocket', 'xdr-streaming', 'xhr-streaming', 'iframe-eventsource', 'iframe-htmlfile', 'xdr-polling', 'xhr-polling', 'iframe-xhr-polling', 'jsonp-polling']
});
};
socket.onopen = function () {
clearInterval(recInterval);
};
socket.onclose = function () {
recInterval = window.setInterval(function () {
new_conn();
}, 2000);
};
无论如何,这很奇怪,因为您在 window
对象上声明了 recInterval
,它应该有效。如果它不起作用,您还可以使用浏览器调试它,使用 debugger;
语句或通过设置本地断点以交互方式...(例如,在 onopen
中) .
顺便说一句,我像这样重写了整个代码(我喜欢重构:):
var recInterval = null;
var socket = null;
var new_conn = function() {
socket = new SockJS(protocol + serverDomain + '/echo', null, {
'protocols_whitelist': ['websocket', 'xdr-streaming', 'xhr-streaming',
'iframe-eventsource', 'iframe-htmlfile',
'xdr-polling', 'xhr-polling', 'iframe-xhr-polling',
'jsonp-polling']
});
socket.onopen = function () {
clearInterval(recInterval);
};
socket.onclose = function () {
recInterval = setInterval(function () {
new_conn();
}, 2000);
};
};
关于javascript - SockJS 客户端自动重新连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18930786/