gpt4 book ai didi

javascript - websockets - 检测具有相同 ID 和 "kick"的多个客户端

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:28:48 25 4
gpt4 key购买 nike

这是我的服务器端 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 的连接。

有没有其他方法或者我的脚本有什么错误?

谢谢

最佳答案

使用 Array 的对象代替 clients 池使其更快更简单:

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;
clients[aqsteamid]=connection;

socket.on('close', function(webSocketConnection, closeReason, description){
try{
console.log('ID',webSocketConnection.ID,'disconnected. ('+closeReason+';'+description+')');
webSocketConnection.balRefreshes = 0;
webSocketConnection.spamcheck = false;
delete clients[aqsteamid];
}catch(e)
{
console.log(e);
}
});

//check if this user is already connected. If yes, kicks the previous client
if(clients[aqsteamid]) clients[aqsteamid].close();
console.log('ID',connection.ID,' connected.');

有了对象池,我们可以去掉所有的数组池循环和比较逻辑,我们的索引永远不会不同步。

关于javascript - websockets - 检测具有相同 ID 和 "kick"的多个客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35917804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com