I have been stuck with this problem for a while now . I want to emit to all the connected clients of a room when a new client joins the room. I have already seen the https://socket.io/docs/v3/emit-cheatsheet/index.html and tried all the emit methods for rooms as seen below in server code and none of them work except the one which emits to all the connected clients and not to a specific room.
Server code
socket.on("newUser", (data) => {
socket.join(data.sessionId);
//not a single one of these works to emit to a specific room
socket.broadcast.to(data.sessionId).emit("userJoin", data);
io.to(data.sessionId).emit("userJoin", data);
io.in(data.sessionId).emit("userJoin", data);
io.sockets.in(data.sessionId).emit("userJoin", data);
//only this works but send to all the clients
io.emit("userJoin", data);
});
client code
//simply adds a div with info to inform other users that a new user has joined
//works only on io.emit() which emits to all the connected clients of every room
socket.on("userJoin",(data)=>{
const users=document.getElementById('users');
const noUsers=document.getElementById('noUsers');
if(data.action==='join'){
const user = document.createElement('article');
user.classList.add('card');
user.classList.add('lobby-item');
user.innerHTML=`<header class='card__header'>
<h1 class='session__id'>
${data.user.name}
</h1>
</header>`;
users.appendChild(user);
}
});
I think the problem with all the room emit methods not working might be with the rooms being formed wrongly or are empty.But still none of the methods for rooms work here.
In socket io if there is a redirect from the app or a refresh from the client there is a new socket.id created which means that the old socket was disconnected and a new one was created.
In my app i was first doing socket.emit()
on the join in route and then redirecting the user to a different lobby route which meant that the socket which joined the room had been disconnected due to redirecting it to lobby and a new socket was created which wasn't in any room.
Therefore io.to(data.sessionId).emit()
wasn't working as all the socket that joined the room were disconnected due to redirecting. io.emit()
works as it emits to all the sockets that are currently connected