1

While I'm learning Node.js, I confronted an example to write a chat system.

Somewhere in the code there's following line:

socket.broadcast
    .to(message.room)
    .emit('message', theMessage);

I don't understand what the to function is doing. Also, I didn't find any clue at the client side code. What happens if the code has not to(message.room) part?

mehrandvd
  • 8,806
  • 12
  • 64
  • 111
  • possible duplicate of [Whats the difference between io.sockets.emit and broadcast?](http://stackoverflow.com/questions/10342681/whats-the-difference-between-io-sockets-emit-and-broadcast) – laggingreflex Jun 20 '15 at 09:44
  • @laggingreflex my specific question is about the usage of `to` method. I already now the difference between `sockets.emti` and `broadcast`. – mehrandvd Jun 20 '15 at 10:45
  • `.to` is for emitting to a room: http://socket.io/docs/rooms-and-namespaces/#rooms – laggingreflex Jun 20 '15 at 11:17

1 Answers1

3

socket.broadcast.to broadcasts to all sockets in the given room, except to the socket on which it was called.

For more details : http://socket.io/docs/server-api/#socket#to(room:string):socket

Pratyush Khare
  • 689
  • 5
  • 16
  • I just don't understand the meaning of room. When you program with sockets in C++ there is no concept like room. Sockets are able to communicate only with messages. – mehrandvd Jun 25 '15 at 08:36
  • By using rooms, you can also define arbitrary channels that sockets can join and leave. This provides a specific event to be emitted to the connected sockets of that room only. I have not used sockets with C++, so I cant help in that. – Pratyush Khare Jun 25 '15 at 11:58