首页 > 解决方案 > socket.io leave current room and join after button is clicked

问题描述

my question is about socket rooms and leave and joining in rooms .my problem is that : i am creating chatroom and i want whenever user (socket) clicks "next person" button (in my case link) i want socket to disconnect (leave) its current room and join another one where another socket is waiting for second socket. like in Omegle

Heading

so i tried this code

client-side:

 N.addEventListener('click', function(e){
                 socket.emit('next')

});

socket.on('next',function(){
socket.disconnect()
document.GetElementById('divd').style.display = "inline";
socket.connect()
});

server-side:

       socket.on('next', function(){
        socket.leave(socket.current_room)
        chnm.in(socket.current_room).emit('next');
        socket.join(room)
        });

but whenever i click "next" it only shows both socket disconnect div like in disconnect event but does not lets socket which triggered that event to join other room rooms in my case is like that

   var room = "room" + numb;
   socket.current_room = room;

but what i want is to show in room (where socket disconnected) that socket disconnected and socket which triggered that event to be joined in other room . (example: in room 1 socket triggered "next" link he/she disconnects from the room 1 and joins to room 2 and in room 1 appears disconnect div, i think it will appear anyway if i use socket.disconnect() because i already created disconnect event . thanks guys for help <3

标签: node.jssocketsexpresssocket.iochatroom

解决方案


仍然没有显示足够的代码或描述您试图实现的整体设计,但这是我从您到目前为止所展示的内容中可以看到的内容。

这是您的事件顺序:

  1. 用户点击按钮
  2. 客户端代码socket.emit('next')
  3. 服务器收到next消息
  4. 服务器调用socket.leave(socket.current_room)离开当前房间
  5. 服务器对.emit('next')仍然在那个房间里的每个人做一个
  6. 服务器调用socket.join(room)(我不知道room变量来自哪里)
  7. 客户端收到next消息并导致他们使用socket.disconnect() and thensocket.connect()`(不知道为什么这样做)。

对于这一系列事件,我觉得奇怪的是:

  1. 其次socket.disconnect()socket.connect()完全没有必要的,可能会导致问题。首先,这些事件是异步的。如果您真的想先做一个,然后再做另一个,则需要等待断开连接完成,然后再尝试重新连接。但是,大多数情况下,应该没有理由断开然后重新连接。只需更新您已有的连接状态即可。

  2. 我不明白为什么当你将某人分配到一个新房间时,你会断开那个房间里的其他人。

  3. 请不要使用相同的消息名称next来表示客户端收到它时的一件事和服务器收到它时完全不同的东西。这本身不是编程错误,但它确实使您的代码难以理解。给每个人自己的描述性名称。


推荐阅读