Socket.io what room(s) is the socket in?

2019-07-15 02:52发布

问题:

I am new to socket.io and unfamiliar with how to deal with their data structures. According to another post, I need to use "socket.rooms" to find out what room a socket is in. Yet if I print out "socket.rooms" in the console log, I get [Object object]. It is some type of object, but without any documentation on how to access that object properly, I am at a loss on what to do.

Very simple code below, I want the "????" to be the room they are in. Obviously, they could be in more than one room, in which case I could build a loop... but for what I am building, they will only ever be in one room.

// Send Message
socket.on('game_update', function(data){

    var tStamp = Date.now();
    console.log(tStamp +" - "+ data.msg);

    io.in('????').emit('game_update', {time: tStamp, msg: data});
});

回答1:

Thanks to @Quentin I was able to figure it out.

console.log(socket.rooms); // prints all elements of the rooms object

A player in Room #82, looked something like:

{ '82': '82', 'oNKayk7Ny8GKh1-4AAAB': 'oNKayk7Ny8GKh1-4AAAB' }

The first element is the room, and the 2nd element is their browser cookie that socket.io creates.

To solve my issue, I need to figure out what element is the room, so '82' is inadequate for what I am doing. I am making the 82 more specific, so I know that the property is the room I am referencing and not their cookie or something else.

socket.join("game_id="+data.game_id); // to join the room, but also id this from other properties

Then the final code I need is:

socket.on('game_update', function(data){

    console.log(socket.rooms); // for debug, prints the data
    var tStamp = Date.now();
    console.log(tStamp +" - "+ data.msg);

    var roomsObj = socket.rooms;

    for(i=0; i < Object.keys(roomsObj).length; i++)
    {
        if(roomsObj[Object.keys(roomsObj)[i]].split("=")[0] == "game_id")
        {
            //broadcasts to every room they are in, which begins in "game_id="
            io.in(roomsObj[Object.keys(roomsObj)[i]]).emit('game_update', {time: tStamp, msg: data});
        }
    }
});

Tested it, and it is working!



回答2:

Socket.IO has changed a lot through different versions. Think of it as a company with poor direction and non solid policies, constantly changing in detriment of their clients (the developers).

Digging into "io" I found this and I've been using it in my last project because I had your same problem:

io.sockets.adapter.sids[socket.id]

If on top of getting the rooms a socket is in you also need to get all sockets inside a room, use the following:

io.sockets.adapter.rooms['nameOfTheRoom'].sockets