简体   繁体   English

node.js加入和离开聊天室

[英]node.js joining and leaving chat room

I am relatively new to node.js and have been looking it up for quite some time now. 我对node.js相对较新,并且已经查找了一段时间。 I have a problem regarding the handling of multiple chat rooms. 我在处理多个聊天室时遇到问题。

When a user connects, they automatically join the room that I have setup. 当用户连接时,他们会自动加入我已设置的会议室。 However, the problems is that the connection is persistent and I wish to address the problem by using the socket.leave(room) method. 但是,问题在于连接是持久的,我希望使用socket.leave(room)方法解决该问题。

My question is, how can this be handled on the client side? 我的问题是,如何在客户端进行处理?

Am I right in putting this on my script? 我把这个放在我的脚本上对吗?

server.js server.js

io.sockets.on( 'connection', function( socket ) {

    socket.on('join', function(room) {
          socket.join(room);
          console.log("User joined "+room);
    });

    socket.on('disconnect', function(room) {
          socket.leave(room);
          console.log("User left "+room);
    });

On the client, how can I trigger the disconnect event? 在客户端上,如何触发断开连接事件? Should I have it called on Page Unload? 我应该在页面卸载上调用它吗?

EDIT: Additional Info 编辑:附加信息

User 1 connects to room 1
User 2 connects to room 1

This is a good and great room connection. 这是一个很好的房间连接。

However, once there's a switch of rooms 但是,一旦换了房间

User 1 connects to room 2
User 3 connects to room 2

User 1 is not able to receive the messages from User 3 because he is still listening to room 1 用户1无法接收来自用户3的消息,因为他仍在收听会议室1

This is the reason why I wish to manage the rooms that the user wishes to join to, hence my question on how to force a User to leave a specific room. 这就是为什么我希望管理用户希望加入的房间的原因,因此是我关于如何强制用户离开特定房间的问题。

Any advice would be greatly appreciated. 任何建议将不胜感激。

If you emit some event like change room from your client code when user changes room like this: 如果在用户更改房间时,您从客户端代码发出某些事件,例如change room ,则:

socket.emit("change room", {newroom: "room name"});

Let's suppose a client has already joined a room as: 假设一个客户已经以以下方式加入会议室:

socket.on('join', function(room){
  socket.room = room;
  socket.join(room);
});

Then you can do this in server to change the room of that client: 然后,您可以在服务器中执行此操作以更改该客户端的房间:

socket.on("change room",function(data){
  socket.leave(socket.room);
  socket.join(data.newroom);
});

You don't have to call socket.leave() in disconnect event. 您无需在disconnect事件中调用socket.leave() You can do it in your own logic. 您可以按照自己的逻辑进行操作。 Hope you can understand this! 希望你能理解!

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

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