【发布时间】:2021-10-15 06:34:26
【问题描述】:
我在我的节点服务器上创建了一个 websocket 客户端,它监听第 3 部分 websocket 服务器。客户端服务器之间的通信都很好,但我面临的唯一问题是当我的服务器重新启动套接字连接代码再次运行并且每次与服务器建立新连接时导致打开的套接字连接过多。我想要做的是当服务器重新启动时关闭所有现有的打开连接然后建立新连接。
const WebSocketClient = require('websocket').client;
let sockets = [];
function openSocket(client,id){
client = new WebSocketClient();
client.on('connectFailed', function(error) {
console.log('Connect Error 1: ' + error);
});
client.on('connect', function(connection) {
console.log('WebSocket Client Connected');
connection.on('error', function(error) {
console.log("Connection Error 2: " + error.toString());
});
connection.on('close', function() {
console.log('echo-protocol Connection Closed');
// setTimeout(run, 1000);
});
connection.on('message', function(message) {
let {utf8Data:socketResData} = message;
// socketResData = JSON.parse(socketResData);
console.log(socketResData);
});
function subscribe(){
if (connection.connected) {
connection.send(JSON.stringify(
{
action: "SubscribeToAuction",
data: id
}
));
}
}
subscribe();
function pingServer() {
if (connection.connected) {
connection.send(JSON.stringify(
{
action: "Ping",
}
));
setTimeout(pingServer, 540000);
}
}
pingServer();
});
client.connect(socketUrl,null,{"x-forwarded-client-id":id},null);
sockets.push(client);
}
function run(){
axios(url, {
method: 'GET',
headers: {
authority,
'x-forwarded-client-id': id,
},
}).then(res => {
const auction = res.data.models.HomePageModel.upcomingModel.upcomingAuctions;
let i = 0;
for(let el of auction){
openSocket(`client${i}`,el.auctionUuid)
i++;
}
}).catch(err => console.log(err))
}
run();
setTimeout(() => {
for(let s in sockets){
console.log(sockets[s]);
sockets[s].close();
}
},10000)
只是为了检查我尝试将所有连接存储在一个数组中然后循环遍历它们并尝试关闭但得到这个错误的可能性
sockets[s].close();
^
TypeError: sockets[s].close is not a function
我只是想知道处理这个用例的最佳方法是什么。任何帮助将不胜感激。
【问题讨论】: