简体   繁体   中英

socket.io: only one room to a socket

I would like to guarantee that a user is only in one room at a time, but I am having trouble implimenting this. I have boiled the issue down to not being able to get a list of all the rooms a socket is currently in.

My current strategy is to do something like this:

io.on('connection', function(socket) {
    console.log('A user just connected with id ' + socket.id);
    socket.on("change room", function(data) {
        // this SHOULD return a list of all rooms this user is in
        var socketsRooms = socket.rooms;
        console.log(socket.rooms) //{ '/#3tE4Up5PRbTfsU0JAAAD': '/#3tE4Up5PRbTfsU0JAAAD' }
        console.log(typeof socket.rooms) // object
        // Loop through the rooms and leave them
        for (var room in socketsRooms) {
            console.log('LEAVING ROOM: ', room);
            socket.leave(room);
        }

        // Join the new room
        socket.join(data.newroom);
    });
    socket.on('disconnect', function() {
        console.log('user ' + socket.id + ' disconnected');
    });
})

Is there an issue in the docs with socket.rooms? It says it should return an array of rooms that a socket is connected to, but I get back data as an id object. EX: { '/#3tE4Up5PRbTfsU0JAAAD': '/#3tE4Up5PRbTfsU0JAAAD' }

... In my case I would expect something like ['issues']

On the Socket.io github page the socket.rooms description stated:

A hash of strings identifying the rooms this socket is in, indexed by room name.

BEFORE MARKING AS A DUPLICATE:

I have already checked out the folowing questions:

  1. How to leave all rooms that the socket is connected to at one go in Node.js
  2. socket.io: assure socket joins only one room at a time

The answer to the first question seems the most hacked together solution the I am pretty sure it will work because it assumes the solution as maintaining our own list, but I would prefer a working solution using socket.io over that method.

I am using the latest verion of socket.io v1.4.5 with angular2 beta on the client (if that helps out at all)

In socket.io, each socket is also connected to its own room. This room has the same name of socket.id . So when leaving the rooms, make sure you don't leave its own room.

for(room in socket.rooms){
    if(socket.id !== room) socket.leave(room);
}
socket.join(data.newroom, function(){
  console.log('rooms', socket.rooms); // here you'll see two rooms: one with socket.id and another with data.newroom
});

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