首页 > 解决方案 > 如何使用 socket.io 发出一个在连接的客户端之间更新的数组

问题描述

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

脚本.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); }));

更新了将服务器用作“主阵列”的代码。

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

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

标签: javascriptnode.jsexpresssocket.iochatroom

解决方案


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

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


推荐阅读