Reputation: 1068
I am trying to achieve the same feature as groups, where a user is connected to more than one room at a time.
Let's imagine two users 1 and 2, respectively connected to the rooms A and B. When I do socket.broadcast.to(A).emit
, both users are getting the message on the same window, even though both of them are connected to different rooms
I get groupsList the user is connected from database. I am using the groupId
for(var i=0;i<groupsList.length;i++){
var groupName = groupsList[i].Id.toString();
socket.join(groupName);
}
Message form Client side is sent using
socket.emit('send-Group-Message', {msg:messageBox.val(),"groupId":$("#connectedGroup").val()});
On the server Side
socket.on('send-Group-Message',function(data){
socket.broadcast.to(groupIdString).emit('group_message',{msg:message,date:Datesent,senderUsername:socket.nickname,senderDisplayName:displayName})
socket.emit('myGroup_message',{msg:message,date:Datesent,senderDisplayName:displayName});
});
then on the client side
socket.on('group_message', function (data) {
chat.append("<div class=\"row\" ><span class='recivedMessage'><div class=\"alert alert-info textWrap\"><b>"+data.senderDisplayName+": </b>"
+ data.msg + "<br><span class=\"date\">"+ data.date.toString() +"</span></div></span></div>");
});
I can check which group is associated to the message from the client side, but I am not sure if this is the right method.
How can I cleanly separate the rooms?
Upvotes: 0
Views: 1110
Reputation: 707456
If a socket can be in more than one room in your app and you want the receiving client to know which room a message was from, then you need to include the room
that the message pertains to in your message broadcast:
socket.broadcast.to(A).emit("newMsg", {room: A, msg: "some Message Here"});
Then, the receiving client gets both the message data and a room name that it corresponds to and the client can then display that message in the corresponding widget on the page that is appropriate for that room.
The broadcast, by itself, does not indicate the room it was broadcast to. A room is really just a server-side concept for grouping sockets. When it goes to broadcast to the room, it literally just gets a list of sockets, iterates through each socket in the list sending the desired message. There is no concept of the room actually sent with the message. So, as I said above, if you want the receiver to know the room a message corresponds to, then you need to explicitly send it with the message.
Upvotes: 4