0
votes

I'm new to socket.io. I have been working on this message chat for a while. I was able to add usernames to the chat when a user logs in and submits a message but for the life of me I can't get it to read the users names when users disconnect. Maybe I've been working on this too long but the answer shouldn't be that hard since I have the usernames working on connect and submit.

This is what I have on the client side.

socket.on('connect', () => {
        // emiting to everybody  
        socket.emit('join', { room: room, name: name });    
      })

name holds the logged in username.

On the server side I have this.

socket.on('join', (data) => {    
    socket.join(data.room); 
    tech.in(data.room).emit('message', `${data.name} joined ${data.room} room!`);
})

socket.on('disconnect', (data) => {
    console.log('user disconnected');
    tech.emit('message', 'user disconnected' + data.name );
})

The connect works fine, when a user connects I get the user's name has joined the room but I get undefined for the disconnect "user disconnected undefined". Not recognizing the var. I'm guessing I need to emit it for disconnect on the client side? This seems like it should be easy but is giving me problems.

Any help would be much appreciated. Thanks.

2

2 Answers

0
votes

On server side, you can do like this:

let users = {}
io.of('/test').on('connection', (socket) => {
    
    socket.on('join', (data) => {
        socket.join(data.room);
        
        users[socket.id] = data;

        io.of('/test').to(data.room).emit('message', `${data.name} joined ${data.room} room!`);
    })
    
    socket.on('disconnect', () => {
        io.of('/test').emit('message', 'user disconnected ' + users[socket.id].name);
        delete users[socket.id];
    })
})

Since you are not storing your event payload, so I stored it in an object 'users'. You can also store it in cache

Also I would like to mention that disconnect event does't support arguments. You can refer from the link below. https://socket.io/docs/v3/client-api/#socket-disconnect

0
votes
  io.use((socket: any, next: any) => {
     //you can do authentication in this middleware
     // you can also validate query data here => socket.handshake.query
     if (authenticated){
         socket.data.groupid = socket.handshake.query.groupid;
         next();
     }else{
         return new Error('Authentication error')
     }
  })
  .on('connection',socket:any) => {

       socket.join(socket.data.groupid, () => {
          // you can join the room from inside here
       });
     
       socket.on('disconnect', () => {
         //you can handle disconnect event here
       });
  })