【发布时间】:2023-03-31 02:35:01
【问题描述】:
这是我的服务器端 websocket 脚本:
var clients = [ ];
//sample request: ****:8080/?steamid=123456789
var connection;
var aqsteamid = getParameterByName("steamid",request.resource);
connection = request.accept(null, request.origin);
connection.ID = aqsteamid;
connection.balRefreshes = 0;
connection.clientIndex = clients.push(connection) - 1;
//check if this user is already connected. If yes, kicks the previous client ***====EDITED====***
for(var i = 0; i < clients.length; i++)
{
if(clients[i].ID === aqsteamid){
var indx = clients.indexOf(clients[i]);
clients[indx].close();
}
}
console.log('ID',connection.ID,' connected.');
socket.on('close', function(webSocketConnection, closeReason, description){
try{
console.log('ID',webSocketConnection.ID,'disconnected. ('+closeReason+';'+description+')');
webSocketConnection.balRefreshes = 0;
webSocketConnection.spamcheck = false;
clients.splice(webSocketConnection.clientIndex, 1);
}catch(e)
{
console.log(e);
}
});
基本上我想要的是踢掉所有具有相同 ID 的连接(例如,连接多个浏览器选项卡)。
但是,它不会踢掉旧客户端,而是踢掉两个客户端,或者在某些情况下,两个客户端都使用相同的 ID 保持连接。
还有没有其他方法或者我的脚本有什么错误?
谢谢
【问题讨论】:
-
clients.splice(webSocketConnection.clientIndex, 1);是问题所在。splice()更改了它前面的元素的索引,因此您的clientIndex属性与clients长时间不一致,这解释了所描述的不稳定症状。您可能需要先使用clients.indexOf()查找连接的当前索引,然后再使用splice() -
顺便说一句,最好使用带有 ID 键的对象,而不是在每个连接事件中循环遍历数组。
used={};.. if(used[aqsteamid]){...}else{used[aqsteamid]=connection}和断开连接时,delete比splice更简单:delete used[webSocketConnection.ID]; -
嘿,谢谢你的回复。我已经稍微改变了循环,但它仍然是一样的。是否必须使用您的 used=[] 示例来完成?
-
你只能做一件事,首先检查连接是否存在然后连接,所以没有机会创建另一个具有相同ID的客户端
-
@dandavis 我忘了在 on('close') 事件中更改脚本,现在似乎工作正常。谢谢,请写一个答案,以便我接受。
标签: javascript websocket