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

damienfrancois
  • 52,978
  • 9
  • 96
  • 110
yanstv
  • 157
  • 1
  • 14
  • See [Socket.io rooms difference between broadcast.to and sockets.in][1] [1]: http://stackoverflow.com/questions/6873607/socket-io-rooms-difference-between-broadcast-to-and-sockets-in – Đức Nguyễn Oct 11 '13 at 07:13
  • The code looks good, maybe, check **data.room**. – Andrew_1510 Oct 24 '13 at 03:06
  • Try this, it used EJS and rooms creation dynamically and save save rooms on servers as well. https://stackoverflow.com/a/72763264/11888809 – SWIK Jun 26 '22 at 16:21

1 Answers1

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

vaibhavmande
  • 1,115
  • 9
  • 17
  • 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 – yanstv Oct 11 '13 at 13:15