skip to Main Content

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


  1. Chosen as BEST ANSWER

    The solution turned out to be simple, the handler had to be moved outside:

    io.on("connection", (socket) => {
         console.log('-----')
    })
    io.sockets.adapter.on("leave-room", (room, id) => {
         console.log('socket '+ id +' left room ' + room)
    });
    

  2. 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:

    io.on("connection", (socket) => {
        console.log("User connected:", socket.id);
    
        socket.on("disconnecting", () => {
            const rooms = Object.keys(socket.rooms); // Get the list of rooms the socket is leaving
            rooms.forEach((room) => {
                console.log("User", socket.id, "left room", room);
            });
        });
    });
    
    Login or Signup to reply.
  3. 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.

    io.on("connection", (socket) => {
        console.log('connected socket ' + socket.id);
    });
    
    io.sockets.adapter.on("leave-room", (room, id) => {
        console.log('socket '+ id +' left room ' + room);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search