简体   繁体   English

NodeJS发射到特定房间[socket.io]

[英]NodeJS emit to specific room [socket.io]

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. 用户加入会议室时,roomID将保存在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 . 现在,假设previousRoomID = 1 ,而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: 如果我在roomID 1中,并且用户离开了该房间,则会收到以下消息:

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. 我不应该看到第二条消息,因为在上面的代码中,我将其发送到io.to(socket.room.id).emit() ,但是即使我在房间1中,我也会收到此消息。

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 . 虽然我不了解广播功能,但从理论上讲,消息应该发送给每个人,但是由于某种原因,调用io.to.emit行的套接字没有收到activity-notification

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM