我试图编写一个连接到WebSocket服务器的函数。此服务器关闭时会出现问题。这个函数应该等待它,即使等待很长时间,但它不应该消耗100%的CPU。这是我的代码:
var state = {
connected: false
};
var settings = {
host: 'localhost',
port: 1988
};
function connect(settings) {
try {
var socket;
var host = 'ws://' + settings.host + ':' + settings.port;
var socket = new WebSocket(host);
socket.onopen = function() {
state.connected = true;
}
// socket.onmessage
socket.onclose = function() {
state.connected = false;
connect(settings);
}
} catch(e){
console.log(e);
}
}
因此,我需要以某种方式将一个间隔传递给WebSocket构造函数,看起来它只是试图在循环中打开一个连接,从而扼杀性能。我该怎么做?
当您尝试连接时,套接字会立即关闭,导致您尝试再次连接。添加尝试间隔:
socket.onclose = function() {
state.connected = false;
setInterval(function() {
connect(settings);
}, 1000);
}