Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading