0

II am here to resolve my problem in socket connection and disconnection. I want something like this

 1. connection done. (ok)  // working 
 2. on perticular event I am doing to update location of user in database { Here user is online }.
 3. But somehow network disconnection the socket will be disconnect and user must be offline. this can be using disconnect event. but I am not aware how to recognise that perticular user has to be updated offline because I don't have user_id in `socket.on('disconnect')` event. please help me out. I googled it everywhere but not helped me out.

sorry for wanting logic but it is really needed to me. Thanks in advance. :)

APr
  • 3
  • 1
  • On socket connection create a new property on socket object like socket_object.user_id = 'XXXXX' and when disconnect event will get executed. You have that user_id on your socket_object, use it as you want to. Or you can use Redis to save socket related data with the socket id as key and when socket disconnects you can get all data from redis and perform the work you want and Remove redis key after this – Jitendra Khatri Jun 02 '16 at 12:33

1 Answers1

0

On disconnect, like you mentioned, you can track the id based on this.id or socket.id.

socket.on('disconnect', function() {
    console.log(this.id);
    console.log(socket.id);
});

Alternatively, you can handle sockets by using a global array, as suggested in this answer.

If netiher of those are suitable, you can do some dependency injection on the socket object

io.on('connection', function(socket) {
    //Obtain the user_id somehow and add it into the socket object
    socket.user_id = "hello_world";

    socket.on('disconnect', function() {
        console.log(socket.user_id);
    });
});
Community
  • 1
  • 1
Rho
  • 370
  • 2
  • 10