1

I have been googling for 2 days on my problem to dynamically create rooms on socket.io using nodeJs. When I create a room to the server, I make it like this:

socket.on('follow_me', function (user_id) { //I use the user_id of the user to create room

    socket.join(user_id);

    console.log(server.sockets.manager.rooms);
});

If next, I want to send a message to all persons connected in the by using

socket.join(user_id);

when i use :

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

    socket.broadcast.to(data.room).emit('recieve',data.message); //emit to 'room' except this socket

});

The other users in this room do not receive the message; but if I use:

socket.join(user_id);`,when i use :

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

    socket.broadcast.emit('recieve',data.message);

});

all user receive the message. Why room do not work for me? I think the code is good!

Tank's

3
  • See [Socket.io rooms difference between broadcast.to and sockets.in][1] [1]: stackoverflow.com/questions/6873607/… Commented Oct 11, 2013 at 7:13
  • The code looks good, maybe, check data.room. Commented Oct 24, 2013 at 3:06
  • Try this, it used EJS and rooms creation dynamically and save save rooms on servers as well. stackoverflow.com/a/72763264/11888809 Commented Jun 26, 2022 at 16:21

1 Answer 1

1
socket.on('message', function (data) {
        /*considering data.room is the correct room name you want to send message to */
        io.sockets.in(data.room).emit('recieve', data.message) //will send event to everybody in the room while 
        socket.broadcast.to(data.room).emit('recieve', data.message) //will broadcast to all sockets in the given room, except to the socket which called it
        /* Also socket.broadcast.emit will send to every connected socket except to socket which called it */
    });

I guess what you need is io.sockets.in

Sign up to request clarification or add additional context in comments.

1 Comment

Tank's for this answer.My problem was an error of me to my side.the io.sockets.in(data.room).emit('recieve', data.message) help to discover the bug in my code and now i continuous to use socket.broadcast.to(data.room).emit('recieve', data.message) without any problem.The code of socket.io was good.tank's to all

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.