The leave-room event fires multiple times. First – 1 time, then – 2 times, then – 3 times, and so on. The same entries are displayed in the console: "user left room A"
Server:
io.on("connection", (socket) => {
console.log('-----')
io.sockets.adapter.on("leave-room", (room, id) => {
console.log('socket '+ id +' left room ' + room)
});
})
After first connection and then disabling in console I have:
-----
socket -PjYaMkMA0g0SAJnAAAB left room -PjYaMkMA0g0SAJnAAAB
After the second connection and then disconnection in the console I have:
-----
socket l7ROvRVqbWb26lL0AAAD left room l7ROvRVqbWb26lL0AAAD
socket l7ROvRVqbWb26lL0AAAD left room l7ROvRVqbWb26lL0AAAD
Next I will have 3 entries, 4, 5 and so on…
Socket.IO version: 4.7.1
3
Answers
The solution turned out to be simple, the handler had to be moved outside:
Instead of using io.sockets.adapter.on("leave-room", …), you should use the socket.on("disconnecting", …) event on the individual socket instance to handle when a user leaves a room.
Here’s the correct way to listen for the user leaving a room using the disconnecting event:
You keep adding a callback function when a connection is made, so it’s normal it’s going to fire more and more after each connection.
I’m not that familiar with socket.io, but you are not using the socket provided by the connect callback, so why can’t you register a callback function outside of the connect event.