Socket Io users Connected to two rooms gets messages from both rooms in same window

时间:2016-10-20 13:03:56

标签: node.js sockets websocket socket.io

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?

1 个答案:

答案 0 :(得分:4)

如果套接字可以位于您应用中的多个房间,并且您希望接收客户端知道消息来自哪个房间,那么您需要在消息中包含消息所属的room广播:

socket.broadcast.to(A).emit("newMsg", {room: A, msg: "some Message Here"});

然后,接收客户端获取消息数据和它对应的房间名称,然后客户端可以在适合该房间的页面上的相应小部件中显示该消息。

广播本身并不表示广播的房间。一个房间实际上只是一个服务器端概念,用于分组套接字。当它进入房间广播时,它实际上只获得一个套接字列表,遍历列表中发送所需消息的每个套接字。实际上没有与消息一起发送的房间的概念。因此,正如我上面所说,如果你希望接收者知道一个消息对应的房间,那么你需要明确地发送消息。