[英]Socket.io array access
我正在使用socket.io和node.js制作一个简单的应用程序,并且我开始考虑从不同事件访问数组。 因此,当有人加入会议室时,我会将他推向所有客户群。 然后,我正在数组中寻找特定的客户端来更改其某些属性。 最终,当客户端断开连接时,我将其从阵列中删除。 在函数找到特定客户端的索引后,客户端断开连接,错误的客户端属性将被更改吗? 这是一段代码
let array=[];
io.on('connection', function (client) {
client.on('join',function(data){
array.push(client);
});
client.on('message',function(data){
let index= findOtherClientIndexInArray();
if(index>-1){
//If client leaves the array is altered so the index is not pointing at correct client
array[index].attribute++;
}
});
client.on('leave',function(data){
array.splice(array.indexOf(client),1)
});
});
不,由于Node.js是单线程环境,因此不再存在index
不再引用同步代码块中数组中的目标客户端的风险。
但是,如果我建议您稍微提高可维护性,则可以使用Set
而不是数组:
let set = new Set();
io.on('connection', function (client) {
client.on('join', function (data) {
set.add(client);
});
client.on('message', function (data) {
// return client directly instead of a key or index
// return undefined or null if none is found
let other = findOtherClientInSet();
if (other) {
other.attribute++;
}
});
client.on('leave', function (data) {
set.delete(client);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.