4

I'm trying to implement a code that shows the list of online users in a site and their last activity time. But a issue I'm facing is that, when the tab is inactive or the user isn't performing any action on the tab, the socket gets disconnected automatically. How can I keep the socket alive if the tab is open regardless active or not.

app.js

...
io.on('connection', function(socket){

  let userName

  socket.on('user viewing', function(user){
    let inActiveUsers = false

    for(var x = 0; x < activeUsers.length; x++) {
        if(activeUsers[x].username == user) {
            inActiveUsers = true
            activeUsers[x].last_activity = MDate.getDateTime()
            break
        }
    }

    if(!inActiveUsers) {
        activeUsers.push({"username": user, "last_activity": MDate.getDateTime()})
    }

    userName = user

    io.emit('active users', activeUsers)

  })

  socket.on('disconnect', function(){

    let userIndex = -1

    for(var x = 0; x < activeUsers.length; x++) {
        if(activeUsers[x].username == userName) {
            userIndex = x
            break
        }
    }

    if(userIndex != -1) {
      activeUsers[x].last_activity = 'NULL'
    }

    io.emit('active users', activeUsers)
  })

})
...

Client side code

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
  socket.emit('user viewing', '<%= user.username %>');
</script>
S. Sandeep
  • 237
  • 3
  • 11
  • Timeout is manged using heartbeat or using ping. You can set these timeouts on the server and if the client has socket.io then the socket will never disconnect automatically until it disconnects if it loses network or a network timeout or someone disconnects. – yash vadhvani Apr 12 '19 at 10:24
  • You have to manage this at application level by adding timeout or something else – yash vadhvani Apr 12 '19 at 10:25
  • @yashvadhvani following your suggestion i did this, but socket io still timesout when page is not in foucs, please check if u can help my question here https://stackoverflow.com/questions/58667207/prevent-socket-io-from-ping-timeout-on-inactive-or-not-focused-browser-page-on-c – Faizan Nov 02 '19 at 00:28
  • Can you modify the client side code to have an interval – yash vadhvani Nov 20 '19 at 08:34
  • – yash vadhvani Nov 20 '19 at 08:35

0 Answers0