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?
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.
You can check the socket. connected property: var socket = io. connect(); console.
To ensure that all data is sent and received before the socket is closed, you should call Shutdown before calling the Disconnect method.
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
socket.io
has a disconnect
event, put this inside your connect
block:
socket.on('disconnect', function () { //do stuff });
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With