It seems that I'm not the only one struggling with this problem.
However I am trying to write a simple chat application. When a user joins a room, the roomID is saved in socket.room.id. It is just a number.
When they join / change rooms, I have the following code:
// Notify the rooms
if(previousRoomID) io.to(previousRoomID).emit("activity-notification","<b>"+socket.me.name+"</b> has left the room " + previousRoomID);
io.to(socket.room.id).emit("activity-notification","<b>"+socket.me.name+"</b> has joined the room " + socket.room.id);
Now, Let's say that previousRoomID = 1
, and socket.room.id = 30
.
It sends the message, but they both seem to go to all users. If I am in roomID 1, and a user leaves the room, I get the following messages:
user has left the room 1
user has joined the room 30
I shouldnt be able to see the second message, because in the code above I am sending it to io.to(socket.room.id).emit()
, yet even when I am in room 1 I am getting this message.
Strangely enough also, It seems to be using the broadcast functionality as well, even though I am not calling it; as in - it sends it to all users except the one who fired the event.
What am I doing wrong?
Okay so I have this figured out. The problem was I was calling
socket.join(roomID)
But I wasn't leaving a room first. So it turns out that a socket can join multiple rooms, which would explain why I was seeing both the messages.
if(previousRoomID) socket.leave(previousRoomID);
socket.join(roomID)
if(previousRoomID) io.to(previousRoomID).emit("activity-notification","<b>"+socket.me.name+"</b> has left the room");
io.to(socket.room.id).emit("activity-notification","<b>"+socket.me.name+"</b> has joined the room");
I dont understand the broadcast functionality though, in theory the messages should be going to everyone but for some reason the socket that calls the io.to.emit
line doesnt get the activity-notification
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.