Socket.io数组访问

时间:2018-08-29 14:23:10

标签: javascript node.js socket.io

我正在使用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)
  });
});

1 个答案:

答案 0 :(得分: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);
  });
});