tidekis doritos
tidekis doritos

Reputation: 47

Chat displays that user disconnects every time user refreshes

The chat's supposed to display to the other users that someone left if he went to another page in the site or if he closed the tab, but to the server refreshing also counts as the user leaving so it displays it again and again on every reload. Is there any way to know if the user refreshed or closed the tab? If not is there anything else to recommend?

Server side : `

    socket.on('disconnect', ()=> {

      const user= userleave(socket.id);

      io.emit('userdisconnected',user)

    })

Front end :

    socket.on('userdisconnected',function outputdisconnect(data){
        
            let div = document.createElement('div')
            div.classList.add('output')
            div.innerHTML = '<p>' + data.username+ ' has left the chat</p>'
            chatwindow.appendChild(div)
        
    })

Upvotes: 1

Views: 99

Answers (1)

Carlo Moretti
Carlo Moretti

Reputation: 2250

Something you could do is waiting 3-4 seconds before sending the userdisconnected and skip it if the same user connects again in that period.

To give a rough idea you could do something like this:

const waitingForDisconnectCheck = {};

const disconnectUserCallback = userId => {
    return () => {
        const user = userleave(userId);
        io.emit('userdisconnected',user)
        delete waitingForDisconnectCheck[userId]
    }
}

socket.on('disconnect', () => {
  waitingForDisconnectCheck[socket.id] = setTimeout(disconnectUserCallback(socket.id), 3000);
})

socket.on('connect', () => {
    waitingForDisconnectCheck[socket.id].clearTimeout()
    delete waitingForDisconnectCheck[userId]
})

Basically when a socket disconnects, you put the relative user in a waiting list, when 3s pass, it will signal disconnection and remove itself form the list, if the user reconnects before timeout, then the timeout is cleared and the user removed from the waiting list.

NB: this works only if socket.id is kept the same over reconnections, otherwise, find a way to identify the user across reconnections.

Upvotes: 2

Related Questions