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
  • 45,247
  • 8
  • 85
  • 92
yanstv
  • 157
  • 1
  • 14

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,074
  • 10
  • 15
  • 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