简体   繁体   中英

How to show online users in socket.io server in node.js?

I am creating a chess game website. I need to show online players available when a user clicks play online. From the online players list the user can click and send them req to play. Now my main problem is I'm new to socket.io and didn't find any resources regarding this online. I am not trying to show the users available in a single room rather the whole socket servers available players. Here Online Players will be shown in a list

function sendName(name) {
  var isNameValid = true;
  for (var i = 0; i < users.length; i++) {
    if (users[i].name === name) {
      isNameValid = false;
      console.log(name + " is already taken");
      console.log(users);
      socket.emit("nameError", "Name already exists, Try again");
      return;
    }
  }
  if (isNameValid) {
    var room = generateRoomId();
    users.push({ id: socket.id, name: name, room: room });
    socket.join(room);
    socket.emit("roomId", room);
  }
}

All the users are pushed in the users' array on the server-side. but I don't know how to get their name and room info on the client-side then show it in the front end.

<div>
            <h3 style="color:white;">Online Players</h3>
                    <ul id="users">
                    </ul>
</div>

Online players will be shown here. Also when one user disconnects the online players' list should refresh which I think socket can do. I am doing a project and any help will be much appreciated and I will learn from it too.

I assume when a users login you add an additional attribute like

socket.user = myUser

Later you can query all sockets that are joined to your room.

async getRoomMembers(room){
    let socketArr = await this.io.of("/").in(room).fetchSockets()
    return socketArr
}

Now all you have to do is go through the array and retrieve the username from the socket object.

This is working for Socket.io 4.3.1

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