【问题标题】:How to associate a socket.id to an array item?如何将 socket.id 关联到数组项?
【发布时间】:2023-03-24 16:07:01
【问题描述】:

我正在尝试创建一个聊天室,其中连接用户的姓名显示在“在线用户”部分。

下面的代码会将每个用户的名字添加到一个数组中并显示数组的内容。

但是,如果用户离开,他们的用户名不会从数组中删除。如果我弹出数组,它可能不会删除正确的用户名。这让我觉得我应该以某种方式将 socket-id 与给定的用户名相关联,并创建一个断开事件,从数组中删除正确的用户名,并显示数组的更新版本。我怎样才能改变这段代码来合并它?

script.js:

var user = user;
if (!user) {
  user = prompt('Please choose a username:');
  if (!user) {
    alert('Your name has been set to "Anonymous"');
    user = "Anonymous"
        items.push(user);
  } else {
      alert('Your name has been set to "'+ user +'"');
  } 
}

socket.emit('theitems', user);

socket.on('theitems', function (data) {
      $('.dispUser').html(data);
      console.log(data);
    });

server.js:

var newitems = [];
server(socket('theitems', ctx => { newitems.push(ctx.data); console.log(ctx.data); ctx.io.emit('theitems', newitems); }));

【问题讨论】:

    标签: javascript arrays node.js express socket.io


    【解决方案1】:

    我相信在用户连接时,您会使用新用户更新您的用户数组,例如:

    let users = [];
    
    sockets.on('connection', socket) => {
        // This is the user associated with a new socket connection. 
        // User that you will need to remove when connection is closed.
        const user = { /* create your user */ };
        users.push(user);
    
        // Then you can subscribe to socket disconnect event
        socket.on('disconnect', () => {
            users = users.filter(u => u !== user); // removing disconnected user
    
            // And then here you can notify your front-end with an updated users array
        });
    });
    
    

    【讨论】:

    • 我实际上设法通过在用户断开连接时清空数组并立即发送连接的名称来为自己解决这个问题。不过,感谢您的宝贵时间!
    猜你喜欢
    • 2015-10-30
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 2012-10-25
    • 2011-03-13
    相关资源
    最近更新 更多