How can I detect disconnects on socket.io?

2020-02-26 04:54发布

问题:

I am using socket.io in my project. I turned on reconnect feature. I want to if user disconnects from server show an alert (Your internet connection loss. Trying reconnect). And if the user reconnects again I want to show one more alert (Don't worry, you are connected).

How can I do it?

回答1:

To detect on the client you use

  // CLIENT CODE
  socket.on('disconnect', function(){
      // Do stuff (probably some jQuery)
  });

It's the exact same code as above for a node.js server too.

If you want for some reason to detect a user disconnecting and display it to the others, you will need to use the server one to detect it the person leaving and then emit back out a message to the others using something like:

socket.on('disconnect', function(){
    socket.broadcast.to(roomName).emit('user_leave', {user_name: "johnjoe123"});
});

Hope this helps



回答2:

socket.io has a disconnect event, put this inside your connect block:

socket.on('disconnect', function () {
    //do stuff
});


回答3:

I handled this problem this way. I've made an emit sender on client which is calling heartbeat on server.

socket.on('heartbeat', function() {
        // console.log('heartbeat called!');
        hbeat[socket.id] = Date.now();
        setTimeout(function() {
            var now = Date.now();
            if (now - hbeat[socket.id] > 5000) {
                console.log('this socket id will be closed ' + socket.id);
                if (addedUser) {
                    --onlineUsers;
                    removeFromLobby(socket.id);

                    try {
                        // this is the most important part
                        io.sockets.connected[socket.id].disconnect();
                    } catch (error) {
                        console.log(error)
                    }
                }
            }
            now = null;
        }, 6000);
    });

I found this code function to call:

io.sockets.connected[socket.id].disconnect();