在服务器端发出插座事件的插座事件是很好的做法吗

发布于 2025-02-11 09:31:28 字数 247 浏览 1 评论 0原文

这种正确的方法/最佳实践是在另一个事件中发射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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心在旅行 2025-02-18 09:31:28

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. When socket.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 the joinRoom event handler and from the createRoom event handler.

You could also combine the logic for joinRoom and createRoom 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文