在服务器端发出插座事件的插座事件是很好的做法吗
这种正确的方法/最佳实践是在另一个事件中发射socket.io事件吗?
// join room
socket.on("joinRoom", async() => {
...
})
// create room and then join room
socket.on("createRoom", async() => {
...
socket.emit("joinRoom")
...
}
Is this correct way/ best practice to emit socket.io event inside another event?
// join room
socket.on("joinRoom", async() => {
...
})
// create room and then join room
socket.on("createRoom", async() => {
...
socket.emit("joinRoom")
...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
socket.emit()
将消息发送到socket.io连接的另一端。您不使用socket.io对自己不.emit()
。当socket.emit(“ joinroom”)
是从您的服务器发送的,它将消息发送给客户端,而不是向服务器发送。因此,这不会做您想做的事情。您可以将代码从
Joinroom
放入共享功能中,并且可以从Joinroom
事件处理程序和createroom
事件处理程序中调用它。您还可以将
joinroom
createroom 的逻辑组合到一个事件中,如果要在加入之前创建的房间,则通过参数传递。然后,“加入”代码在两个操作中都在本地。socket.emit()
sends a message to the OTHER end of the socket.io connection. You do not.emit()
to yourself with socket.io. Whensocket.emit("joinRoom")
is sent from your server, it sends a message to the client, not to your server. So, that won't do what you want it to do.You can put the code from
joinRoom
into a shared function and you can call it from both thejoinRoom
event handler and from thecreateRoom
event handler.You could also combine the logic for
joinRoom
andcreateRoom
into one event where you pass an argument if you want the room created before joining. Then, the "join" code is right there locally for both operations.