0

I am using socket.io for node platform with v2.0.3.

Below code working before a week

socket.broadcast.to(msg.receiverID).emit('new message', { "username": msg.username, "message": msg.message, "to": msg.to, "receiverName": msg.receiverName, "senderName": msg.senderName, "dateTime": data.created });

It's working and emit the message to a single receiverID.But now it doesn't work even i have not modified the previous code. But we have found one of the solution for this is to try the io object to emit the message as mentioned below:

io.to(msg.to).emit('new message', { "username": msg.username, "message": msg.message, "to": msg.to, "receiverName": msg.receiverName, "senderName": msg.senderName ,"dateTime":data.created});

Why this conflicts is socket.broadcast.to() is depricated or unused as of io.to().

  • Possible duplicate of [Whats the difference between io.sockets.emit and broadcast?](https://stackoverflow.com/questions/10342681/whats-the-difference-between-io-sockets-emit-and-broadcast) – David R Sep 07 '17 at 05:34
  • maybe u need a update of node version , and yes "io.to" will also work, https://socket.io/docs/emit-cheatsheet/# – Nilasis Sen Sep 07 '17 at 05:36

1 Answers1

0

socket.broadcast.to(someRoomOrId).emit(...) will send to all sockets in the room or matching the ID except socket. So, if what you're seeing is that it isn't being sent to socket, then that's how this is supposed to work.

If you want to send to all matching sockets, then use:

io.to(someRoomOrId).emit(...)

instead. The socket.to() version is specifically meant to exclude the socket object itself. Here's some of the doc for socket.to():

Sets a modifier for a subsequent event emission that the event will only be broadcasted to clients that have joined the given room (the socket itself being excluded).

jfriend00
  • 683,504
  • 96
  • 985
  • 979