所以,我的socket.join调用什么也没做。在调用socket.join,然后列出套接字所在的房间后,套接字仅连接到由其id(它自己的房间)定义的房间。
function onJoin(room) {
console.log("Joining room: " + room);
socket.join(room);
console.log(socket.id + " now in rooms ", socket.rooms);
}
会打印例如:
> Joining room: 5aba92759b9ffa9fdf579714d6aa125ddb05cb1172611331775e7a69dab37258
> Q6D4h17DvdOZrbrEAAAC now in rooms { Q6D4h17DvdOZrbrEAAAC: 'Q6D4h17DvdOZrbrEAAAC' }
如果它有所不同,这就是我的套接字服务器的创建方式:
//app.js
var app = express();
var http = require('http');
var server = http.Server(app);
var io = require('socket.io')(server);
var chat = require('./routes/chat/chat')(io);
//chat.js
module.exports = function(io) {
io.sockets.on('connection', function(socket) {
socket.on('join', onJoin);
...
}
问题出在哪里?
答案 0 :(得分:3)
问题是socket.join
是异步的。所以这将按预期工作:
socket.join(room, function() {
console.log("Socket now in rooms", socket.rooms);
});
答案 1 :(得分:1)
在新版本中,添加一个函数作为 .join() 方法的第二个参数已被删除, 您可以使用异步等待。
示例
await socket.join(room_Name);
io.to(room_Name).emit(emit_Name);
答案 2 :(得分:0)
使用:io.sockets.adapter.rooms
function onJoin(room) {
console.log("Joining room: " + room);
socket.join(room);
console.log(socket.id + " now in rooms ", getRoomsByUser(socket.id));
}
function getRoomsByUser(id){
let usersRooms = [];
let rooms = io.sockets.adapter.rooms;
for(let room in rooms){
if(rooms.hasOwnProperty(room)){
let sockets = rooms[room].sockets;
if(id in sockets)
usersRooms.push(room);
}
}
return usersRooms;
}
加入'测试'你会看到这样的东西:
AEi6eIlkutIcm_CwAAAB now in rooms test,AEi6eIlkutIcm_CwAAAB
答案 3 :(得分:0)
对于从socket.IO 3.0版开始使用v3.0的任何人,加入不再是异步的,上面的代码应该可以正常工作。 see here