Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect disconnects on socket.io?

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?

like image 311
user2997295 Avatar asked Nov 15 '13 17:11

user2997295


People also ask

How do I know if my client Socket is disconnected?

select (with the read mask set) will return with the handle signalled, but when you use ioctl* to check the number of bytes pending to be read, it will be zero. This is a sign that the socket has been disconnected.

How do I check my Socket.IO connection status?

You can check the socket. connected property: var socket = io. connect(); console.

What must be done before disconnecting a Socket?

To ensure that all data is sent and received before the socket is closed, you should call Shutdown before calling the Disconnect method.


3 Answers

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

like image 159
roryhughes Avatar answered Oct 31 '22 16:10

roryhughes


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

socket.on('disconnect', function () {     //do stuff }); 
like image 38
tymeJV Avatar answered Oct 31 '22 15:10

tymeJV


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();
like image 32
InvincibleTrain Avatar answered Oct 31 '22 17:10

InvincibleTrain