当用户与node.js服务器断开连接时,删除数组项

remove array item when user disconnects from node.js server

本文关键字:删除 数组 连接 断开 用户 node js 服务器      更新时间:2023-09-26

我试图通过构建一个谁能先按下按钮的小游戏来学习nodeJs,

当一个用户加入到一个名为"room"的数组中,这个数组保存了他们的用户名和分数,然后广播到所有连接的客户端,让他们知道谁在房间里

room.push({userName:userName,score:0});
var userName_json = JSON.stringify({ type:'userName', data: userName });
broadcastMessage(userName_json);

广播它们将添加一个HTML元素到页面

      connection.onmessage = function (message) {
      if (json.type === 'userName') {
      addUser(json.data);
    }
  function addMessage(userName) {
    $('#' + userName).addClass('green');
    console.log(userName + 'hits first');
  }

当用户与节点服务器断开连接时,他们需要从这个房间中删除

 connection.on('close', function(connection) {
    if (userName !== false) {
      console.log('user name is not false lets splice');
      console.log((new Date()) + " Peer "
          + connection.remoteAddress + " disconnected.");
      clients.splice(index, 1);
      room.splice(index, 1);
      var userName_json = JSON.stringify({ type:'retire', data: userName });
      broadcastMessage(userName_json);
    } else {
      console.log('cant do anything userName is false');
    }
  });

删除用户HTML元素

    connection.onmessage = function (message) {
else if (json.type === 'retire') {
      console.log(json);
      retireUser(json.data);
    }
function retireUser(userName) {
    $('#' + userName).remove();
    console.log(userName + ' cant handle the pressure');
  }

如果一个用户加入房间然后离开,如果一个用户加入一个已经有人在的房间,或者一个用户在他们之后加入,然后他们试图离开,用户并不总是从房间数组中删除,或者仍然连接的人从页面中删除了他们的html元素。

有什么好主意吗?

全文https://gist.github.com/jkirkby91/9f93ed2cf4e1aa7870e7

我使用map/object来存储key/val数据,而不是array。

next_uid = 0;
users = {};
wsserver.on('connection', function (conn) {
        conn.user_id = ++new_uid; // you can store user-ID here
        users[conn.user_id] = { /* any user data you want */ }
        conn.on('message', function (message) {
                 console.log('message form ' + conn.user_id);
        });
        conn.on('close', function (code, reason) {
                console.log(conn.user_id + ' disconnected');
                delete users[conn.user_id];
        });
}

我发现的一个问题是:您不能假设索引将保持不变。如果删除具有较小索引的不同连接,则上面的所有索引都移动-1。当你删除

时,你必须找出索引
  var index = clients.indexOf(connection);
  clients.splice(index, 1);
  room.splice(index, 1);

我也认为使用用户名作为html id不是一个好主意,特别是如果他们可以包含空格。相反,您应该为每个用户分配一个唯一的数字作为id。