SocketIO Detect Disconnection

I've been trying out socketio in nodejs recently. I know the question has already been asked however I kind of what it to be more specific, with my concern at least.

Basically my issue is that, I have already created a real time live chat and able to determine if someone joins in, but is only limited to that. What I want is to be able to detect the specific user who logged out. By logging out, I mean closing the window (as I have not incorporated any logging in or logging out with actual credentials such as username or password).

Here is my sample code for chat.js:

// Listen for Events
socket.on('chat', function(data){
    feedback.innerHTML = "";
    output.innerHTML += '<p><strong>' + data.handle + ': </strong><br/>' + data.message + '</p>';
});

socket.on('typing', function(data){
    feedback.innerHTML = '<p><em>' + data + ' is typing a message...</em></p>';
});

socket.on('user joined', function(data){
  output.innerHTML += '<p><strong>' + data.username + ' joined! ' + '@' + data.time + '</strong></p><br/>';
});

Now here is my code for index.js:

socket.on('chat', function(data){
    data.handle = '(' + (!userName ? (ipAdd + noUser) : userName) + ') ' + data.handle + ' @' + userDate;
    io.sockets.emit('chat', data);
});

socket.on('typing', function(data){     
    socket.broadcast.emit('typing', data);
}); 

socket.broadcast.emit('user joined', {
    username: (!userName ? (ipAdd + noUser) : userName),
    time: userDate
});

If you are a bit confused with my setup, I used this link as my reference: https://www.youtube.com/watch?v=vQjiN8Qgs3c

Please see tutorial 1 to 5 of the link I've provided.

Thanks

1 answer

  • answered 2018-07-11 03:15 DayIsGreen

    As answered by Li357 (please his comment to my question above), the event disconnect will allow you to detect in real time who got disconnected.