Reputation: 11214
I've put together a chat application where people can join/leave rooms. I have come across something very strange and I really can't get my head around it.
This is an excerpt from my server.js (backend):
client.on("send", function(msg) {
console.log("Sending to ==> " + client.room);
if ('undefined' !== typeof client.room) {
socket.sockets.in(client.room).emit("chat", people[client.id], msg);
}
});
I'm essentially 'forcing' people to join a room (if they are not in a room, client.room returns undefined.)
I have placed two buttons on the frontend, one to join a room and one to leave a room. The join button is handled via:
client.on("joinRoom", function(name) {
client.join(name); //where name is the name of the room coming from the frontend
}
The leave room function looks like this:
client.on("leaveRoom", function(name) {
client.leave(name);
}
Now, the problem is this: after the client.leave(name); bit, the user can still send a message, and console.log("Sending to ==> " + client.room); will still output 'Sending to ==> room1') whereas the client has left the room. I confirmed this with "socket.sockets.clients(client.room)" - the client is not listed here anymore.
Does anyone have any idea why I still emit message from a client to a room that his not part of?
UPDATE
After the answer from DRC, I have updated my send function:
client.on("send", function(msg) {
for (key in socket.sockets.manager.roomClients[client.id]) {
if (key ==="/" + client.room) {
socket.sockets.in(client.room).emit("chat", people[client.id], msg);
}
}
});
Is this the most elegant solution?
Upvotes: 0
Views: 836
Reputation: 5048
you are assigning client.room , and not deleting it whenever the client leaves the room, socket.io is not checking about authorizations for that, you must.
So do a delete client.room whenever the client leaves the room or check if the user is in a room checking the content of io.sockets.manager.roomClients[socket.id]
, see the docs
UPDATE after op question mod.
you already have the room name, so the key for roomClients[socket.id], you could check:
if (socket.sockets.manager.roomClients[client.id]['/'+client.room] !== undefined ){
//the user is part of this room
}
but yes that is the logic.
Upvotes: 1