1

I currently use the following code to allow users to create/join a specific room in socket.io:

socket.on('create', function (roomId) {

    ...

    socket.join(roomId);

    ...

});

since the join function is used for both creating AND joining the same room, I would like tell the client if he was the one that created the room or just joined an existing one.

WHAT I TRIED TO DO

I tried to store the Id (and other informations not related to the problem), then check whenever that id already exists and emit a different message depending on the results. something like:

// "repo" is a variable declared globally

socket.on('create', function (roomId) {

    ...

    socket.join(roomId);

    if (repo.hasRoom(roomId)) {
        app.io.sockets.in(roomId).emit('someone Joined');
    } else {
        app.io.sockets.in(roomId).emit('someone Created this room');
        repo.saveRoom(roomId);
    }


    ...

});

the above code doesn't work, as the client is unable to receive the message emitted (I guess because is on the "create" event). to be clear, I CAN determine on the server if a room is created, but the CLIENT doesn't know.

Is there an effective way to notify the client if he was responsible for creating or just joining a room?

  • 1
    `join` should accept a callback as a second argument- can you leverage that to your advantage, maybe? There's a [related issue](https://github.com/socketio/socket.io/issues/2117) that might have an impact on your desired behavior, though. – Connor Mar 20 '16 at 21:55
  • very interesting. I'll have a go and let you know the outcome :) at least (even if the bug is in place) I can have a callback when the room is created. I just need to code in a way that works even when the bug will be fixed. – Massimo Franciosa Mar 21 '16 at 09:13
  • I don't suppose checking the number of sockets in a room in that callback would be a way to determine if the room has been created or joined, would it? If there's only one socket in the room then it's just been created- more than that, and the socket doing the joining has joined an existing room instead. Thoughts? – Connor Mar 21 '16 at 17:28
  • Thanks, using the callback on emit worked :) what i did is to move the "if(repo.hasRoom)" check into the callback and emit a different signal depending on the outcome. the I catch from the client the related signal received. if you write the solution i can accept it :) – Massimo Franciosa Mar 21 '16 at 21:35
  • No worries- you found the solution, I just kind of offered a suggestion. Either way, glad you could resolve your issue! – Connor Mar 22 '16 at 12:58

0 Answers0