如何连接到几个WebSocket,这些WebSocket在Javascript上提供相同的数据以实现冗余,这样,如果一些



目的是让多个websocket冗余相同的数据,这样,如果其中一个失败,其他的仍然可以完成任务。特别是,任何一个websocket的设置都足以使系统保持工作,即使所有其他websocket都无法连接或返回错误。

这是当前的设置,但我知道它是错误的:

let queue = []        
ws = new WebSocket(`wss://firstsource.com/ws/`);
ws2 = new WebSocket(`wss://secondsource.com/ws/`);
ws3 = new WebSocket(`wss://thirdsource.com/ws/`);
ws4 = new WebSocket(`wss://fourthsource.com/ws/`);
ws.onopen = sendIntro;
ws2.onopen = sendIntro;
ws3.onopen = sendIntro;
ws4.onopen = sendIntro;
ws.onmessage = insertQueue;
ws2.onmessage = insertQueue;
ws3.onmessage = insertQueue;
ws4.onmessage = insertQueue;

function sendIntro() {
ws.send('{"config":"2.0"}')
ws2.send('{"config":"2.0"}')
ws3.send('{"config":"2.0"}')
ws4.send('{"config":"2.0"}')
ws5.send('{"config":"2.0"}')
}

function insertQueue(msg) {
//let's just assume all we want is add the data to a queue
queue.push(msg); 
}

正确的方法是什么?假设所有来源的数据格式相同。

我曾考虑创建一个onError函数,并使用它连接到第二个websocket,然后使用另一个onError2连接到第三个websocket,依此类推,但当没有响应时,触发onError需要很长时间,所以如果像这样串行测试一些源的完整过程会花费太长时间。

找到了一个有效的解决方案。

我想我所需要的只是确保他们中至少有一个连接,而不是确保如果其中一个断开连接,其他人将准备接管。

对于这个减少的问题,这起到了作用:

//defined higher up
let sucessfulFirstSocketConnection = false
function sendIntro1() {
if(!sucessfulFirstSocketConnection){
sucessfulFirstSocketConnection = true
ws.send(sendString)
ws.onmessage = insertQueue;
ws2.close();
ws3.close();
ws4.close();
ws5.close();
}
}
function sendIntro2() {
if(!sucessfulFirstSocketConnection){
sucessfulFirstSocketConnection = true
ws2.send(sendString)
ws2.onmessage = insertQueue;
ws.close()
ws3.close();
ws4.close();
ws5.close();
}
}

等等

我基本上让他们自己竞争,第一个连接的连接关闭了其他连接,阻止了所有其他人的阻碍。即使只有最后一个WebSocket能够连接,而所有其他WebSocket都没有建立连接,这一点也能很快实现。

最新更新