如何将socket.id与数组项关联



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

下面的代码将把每个用户的名称添加到数组中,并显示数组的内容。

但是,如果用户离开,他们的用户名不会从数组中删除。如果我弹出数组,它可能不会删除正确的用户名。这让我觉得我应该以某种方式将套接字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); }));

我相信在用户连接时,您可以用新用户更新您的用户阵列,类似于:

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
});
});

最新更新