简体   繁体   中英

Trouble understanding sockets.io room

I am trying to configure a 1v1 game with multiple rooms on my server with sockets.io. When the user create a room, a random alphanumeric identifier of 5 letters is generated and the user joins the room.

 function handleNewGame() {
        let roomName = makeid(5);
        client.join(roomName);
  }

Then another user is supposed to join with the room name. The room name is taken from a tag inside the html main page and then is sent by a function. This is the function that handles game joining on server side

function handleJoinGame(roomName) {
        const room = io.sockets.adapter.rooms[roomName];
}

All of this is wrapped inside an

io.on('connection', client => {
}

The problem is that at this point, before the other user even tries to join, the room is undefined.

console.log(room);

This gives me undefined. If I try to actually print out all the rooms, it actually exist, but the method can't find it. What did I do wrong?

Forget the library for a moment. Conceptually, a room is just a group of users. an array of socket connections to whom you broadcast using a for loop. It should come with a room manager since you want to have many rooms otherwise you had single room anyway.

Let's assume an object of arrays.

var roomManager = {
  "room12345" : [socket1, socket2, socket5],
  "room76432" : [socket3, socket4],
}

and when socket1 wants to broadcast, you know its room room12345 so you broadcast to all others in that room.

So really you can implement this logic yourself quite easily.

Actually, the io.sockets.adapter.rooms returns a Map. Said so, I had to get the room with a key, using

const room = io.sockets.adapter.rooms.get(roomName);

I've solved the issue.

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