简体   繁体   中英

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

I'm trying to display the usernames of all connected clients in my chat room by adding their username to an array. Currently, my code will just update the user-list with the most recent username to have joined, rather than add the username to the array, leading me to believe the array isn't actually being emitted in the way I anticipate?

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

Updated code that uses the server as a 'master array'.

This code (+ some of the above) has solved my issue.

index.js (server):

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

script.js (client):

socket.emit('theitems', user);

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

It's simple, just socket.emit('eventName', array);

But if you change items of array, it's not gonna change in all socket clients and/or server. You need to emit new array every time that array has changed. Otherwise sockets are not gonna update their values

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.

To do that, you have two choices. Whenever the array changes on the server you have to either send a new copy of the full array of names to each client and they then update their entire user list display or you tell them exactly which user has been removed or added and they then incrementally update their display based on the change.

To send the whole array to one specific socket, you would do something like this:

socket.emit('userList', userArray);

To send it to all connected uses, you would do this:

io.emit('userList', userArray);

In both cases, the client would listen for the 'userList' message and then update their display accordingly.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM