node.js - 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
解决方案
仍然没有显示足够的代码或描述您试图实现的整体设计,但这是我从您到目前为止所展示的内容中可以看到的内容。
这是您的事件顺序:
- 用户点击按钮
- 客户端代码
socket.emit('next')
- 服务器收到
next
消息 - 服务器调用
socket.leave(socket.current_room)
离开当前房间 - 服务器对
.emit('next')
仍然在那个房间里的每个人做一个 - 服务器调用
socket.join(room)
(我不知道room
变量来自哪里) - 客户端收到
next
消息并导致他们使用socket.disconnect() and then
socket.connect()`(不知道为什么这样做)。
对于这一系列事件,我觉得奇怪的是:
其次
socket.disconnect()
是socket.connect()
完全没有必要的,可能会导致问题。首先,这些事件是异步的。如果您真的想先做一个,然后再做另一个,则需要等待断开连接完成,然后再尝试重新连接。但是,大多数情况下,应该没有理由断开然后重新连接。只需更新您已有的连接状态即可。我不明白为什么当你将某人分配到一个新房间时,你会断开那个房间里的其他人。
请不要使用相同的消息名称
next
来表示客户端收到它时的一件事和服务器收到它时完全不同的东西。这本身不是编程错误,但它确实使您的代码难以理解。给每个人自己的描述性名称。
推荐阅读
- c# - 如何将多个单元格与文本连接起来?
- c# - '无法在 MVC Visual Studio 2017 SignalR 中找到程序集 'System.Diagnostics.DiagnosticSource,版本 = 4.0.2.1
- java - 为什么private修饰符使程序在通过子类对象调用的情况下执行超类中的私有方法?
- excel - xlDialogChartSourceData 的参数是什么?
- javascript - socket.io 连接返回一个空数组。在不重新加载页面的情况下在 React 中接收数据的方法?
- android - 对话框警报单击时应用程序崩溃
- javascript - 如何修复“错误类型错误:data.slice 不是函数”?
- python - 在python中导入网格
- apache-spark - Spark 自定义日志记录
- python-3.x - 为什么我的仪表板应用程序无法正确更新?