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?
Joining and leaving In that case, a union is performed: every socket that is at least in one of the rooms will get the event once (even if the socket is in two or more rooms). In that case, every socket in the room excluding the sender will get the event. To leave a channel you call leave in the same fashion as join .
As explained above, getting started with Socket.IO is relatively simple – all you need is a Node. js server to run it on. If you want to get started with a realtime app for a limited number of users, Socket.IO is a good option. Problems come when working at scale.
socket.io rooms are a lightweight data structure. They are simply an array of connections that are associated with that room. You can have as many as you want (within normal memory usage limits).
The 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With