gpt4 book ai didi

Node.js Socket.IO 监听房间连接的最佳方式?

转载 作者:太空宇宙 更新时间:2023-11-03 23:44:15 24 4
gpt4 key购买 nike

我的坏方法

客户端

socket.on('connect',function(){ socket.emit('EnterRoom',{room:'test'});})

服务器端
应用程序.js

io.sockets.on('connection',function(socket){
socket.on('EnterRoom', function(data) {
socket.join(data.room);
app.emit('event:JoinRoom',{room:data.room});
})});

some-module-with-rooms.js

app.on('event:JoinRoom',function(data){if(data.room=='test'){/*anycode*/} });

最佳答案

来自Wiki关于Rooms :

Emitting an event to all clients in a particular room:

io.sockets.in('room').emit('event_name', data)

所以在你的情况下:

io.sockets.on('connection',function(socket){
socket.on('EnterRoom', function(data) {
socket.join(data.room)
io.sockets.in(data.room).emit('JoinRoom', data);
})
});

这只会发射到选定的房间。您可以访问房间:

io.sockets.manager.rooms

我引用了文档:

This is a hash, with the room name as a key to an array of socket IDs. Note that the room names will have a leading / character

关于Node.js Socket.IO 监听房间连接的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16760156/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com