如何使用 socket.io 发出跨连接的客户端更新的数组

How to emit an array that updates across connected clients with socket.io

我试图通过将用户名添加到数组来显示聊天室中所有已连接客户端的用户名。目前,我的代码只会用最近加入的用户名更新用户列表,而不是将用户名添加到数组中,这让我相信数组实际上并没有按照我预期的方式发出?

script.js:

var items = [];
var user = user;
if (!user) {
  user = prompt('Please choose a username:');
  items.push(user);
  socket.emit('theitems', {
      items: items
});
  if (!user) {
    alert('Your name has been set to "Anonymous"');
    user = "Anonymous"
        items.push(user);
  } else {
      alert('Your name has been set to "'+ user +'"');
  } 
}
console.log(items);

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

index.js

server(socket('theitems', ctx => { console.log(ctx.data); ctx.io.emit('theitems', ctx.data); }));

更新代码,将服务器用作 'master array'。

这段代码(+上面的一些代码)解决了我的问题。

index.js(服务器):

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

script.js(客户端):

socket.emit('theitems', user);

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

很简单,就socket.emit('eventName', array);

但是如果你改变数组的项目,它不会在所有套接字客户端and/or服务器中改变。每次该数组更改时,您都需要发出新数组。否则套接字不会更新它们的值

Sorry; my idea is that there’s an array (items[]) that stores the usernames of clients as they join and leave, and displays that array to a , so, that, as clients join and leave, their usernames are displayed/removed, aka, an “online users” section.

为此,您有两种选择。每当服务器上的数组发生变化时,您必须向每个客户端发送完整名称数组的新副本,然后他们更新他们的整个用户列表显示,或者您确切地告诉他们哪个用户已被删除或添加,然后他们逐渐更新他们的显示基于变化。

要将整个数组发送到一个特定的套接字,您可以这样做:

socket.emit('userList', userArray);

要将其发送给所有连接的用户,您可以这样做:

io.emit('userList', userArray);

在这两种情况下,客户端都会侦听 'userList' 消息,然后相应地更新它们的显示。

socket.on('userList', userArray => {
    // refresh  the display to show the userArray
});