So, my socket.join calls are doing nothing. After calling socket.join, and then listing the rooms the socket is in, the socket is only connected to the room defined by it's id (it's own room).
function onJoin(room) {
console.log("Joining room: " + room);
socket.join(room);
console.log(socket.id + " now in rooms ", socket.rooms);
}
Would print for example:
> Joining room: 5aba92759b9ffa9fdf579714d6aa125ddb05cb1172611331775e7a69dab37258
> Q6D4h17DvdOZrbrEAAAC now in rooms { Q6D4h17DvdOZrbrEAAAC: 'Q6D4h17DvdOZrbrEAAAC' }
If it makes a difference, here's how my socket server is being created:
//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);
...
}
Where's the issue?
- Socket.io v1.7.3
So, my socket.join calls are doing nothing. After calling socket.join, and then listing the rooms the socket is in, the socket is only connected to the room defined by it's id (it's own room).
function onJoin(room) {
console.log("Joining room: " + room);
socket.join(room);
console.log(socket.id + " now in rooms ", socket.rooms);
}
Would print for example:
> Joining room: 5aba92759b9ffa9fdf579714d6aa125ddb05cb1172611331775e7a69dab37258
> Q6D4h17DvdOZrbrEAAAC now in rooms { Q6D4h17DvdOZrbrEAAAC: 'Q6D4h17DvdOZrbrEAAAC' }
If it makes a difference, here's how my socket server is being created:
//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);
...
}
Where's the issue?
- Socket.io v1.7.3
4 Answers
Reset to default 12The issue was that socket.join
is async. So this would work as expected:
socket.join(room, function() {
console.log("Socket now in rooms", socket.rooms);
});
In the new version, adding a function as a second parameter to the .join() method has been removed, You can use async await.
example
await socket.join(room_Name);
io.to(room_Name).emit(emit_Name);
Use: 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;
}
After joining 'test' you will see something like this:
AEi6eIlkutIcm_CwAAAB now in rooms test,AEi6eIlkutIcm_CwAAAB
For anyone using v3.0, from socket.IO version 3.0, join is no longer asynchronous and the above code should work just fine. see here