Detect client's disconnection WebSocket - javascript

I'm using WebSocket & nodeJs. I can detect user's connection and present it, but I can't detect user's disconnetion. The method on('close',function()....) happens when I shut down the server and not when a user closes the tab or something. What can I do? I realy don't know how to do it right now. Thank you all! Hoping you'll help me.

To detect socket disconnection, I use this method which works fine :
socket.once('disconnect', function () {
// socket is disconnected
});
Or
socket.on('disconnect', function () {
// socket is disconnected
});
Hope it helps.

You should implement heartbeat requests (inside websocket connection) from client to server (every 20-30 sec) and limit connection to some period (40-50 sec) - this can be done in web server (or even load balancer settings).
When server find that there is no heartbeat request it means that this connection is broken - client closed tab or something.
Updated: oh! Seems socket.io have heartbeat implementation, so my answer was a bit common.

io.sockets.on('connection',function(socket){
socket.on('disconnect', function(){
// Your stuff here
});
});

Related

Check if socket.io server is online from client

I am trying to make a simple socket.io game. I have a login screen, where you enter your username and password, and then you click a big connect button and then you're in (if the client manages to connect to the server). I would like to have a status box on the login screen, so you can see if the server is up or down. I am wondering if there is some sort of ping function in socket.io. Otherwise, could you try to connect to the server (for example, I don't know what's good) 4 times. If it fails, it calls a function/sets a variable, whatever. If it succeeds it calls a function or something, then it disconnects. I have googled around a bit, but can't find anything. (By the way, sorry if this is really noobish, and there is a really apparent solution. I'm new to socket.io 😅) All help will be deeply appreciated!
Socket io has an event listener for this situation. Reconnecting event will fire when socket.io tries to connect but fails. Its a bit misleading cuz it won't fire on every reconnect just when the reconnect try fails.
socket.on('reconnecting', function reconnectCallback(tries) {
if (tries === 3) {
//handle your offline mode here
}
});
socket.on('connect', function connectCallback() {
//handle successful connection here then disconnect
socket.disconnect();
});

autobahn (node) not detecting dropped connect, infinite wait, can I set a timeout?

I'm using this AutobahnJS code in node to receive data from a service. It works great, getting multiple events per second. When my internet temporarily disconnects Autobahn does not detect the lost connection and does not write "Websocket connection dropped" to console, it just hangs. Indefinitely.
Is there a timeout one can set, if no data arrives after 1 minute, reconnect? Or can I use a setTimeout function to ping a server and if no pong returns close the connection and try to reopen it?
I googled till my fingers were bleeding, but I didn't find a straightforward answer to this question. Thank you very much!
connection.onopen = function(session) {
session.subscribe(arg, someEvent);
}
connection.onclose = function() {
console.log("Websocket connection dropped");
}
connection.open();
It is not possible to recognize an unclean disconnect without some data being sent. The WebSocket ping/pong mechanism at the protocol level is not exposed in the browser, and Autobahn|JS does not have any different handling when running in Node.js.
For the time being, you need to implement your own ping/pong mechanism at the application level.

socket.io 'disconnect' not called if page refreshed fast enough

I have the following abridged code:
io.on('connection', function(client) {
client.uuid = uuid.v4();
// add client object to server...
console.log('socket.io:: client connected ' + client.uuid );
client.on('disconnect', function() {
console.log('socket.io:: client disconnected ' + client.uuid );
// remove client object from server...
});
});
If I open up this page in the browser, everything seems fine. If I refresh the page, it will fire disconnect and then connection. However, if I refresh fast enough, there are times where disconnect doesn't get called and thus client data doesn't get cleaned from the server. Is there any way to protect from this?
Edit: reword reconnect -> connection
As adeneo mentioned, socket.io has heartbeats which automatically check to see if a client is still connected. The disconnect code is fired if it detects the client is actually gone. After replicating my original issue, I tried leaving the server on, and about 30 seconds later, the "dead" clients were being removed. So to solve the issue, you just have to wait. Socket.io takes care of everything on its own.
The same question was answered here.
TL;DR
You can use those options on the client:
const socket = io({
transports: ['websocket'],
upgrade: false
});
This will prevent socket.io from using the HTTP polling method at all, which causes the issues. I used this trick successfully on v4.

Socket.IO: Detect disconnected sockets

I have a socket.io server/client. When a client safely disconnects, on the server side, the line
socket.on('disconnect', function() {
});
is called.
However, if the client server crashes, then socket.on('disconnect') is never called; I know this because I recursively print out wss.sockets.connected.length and the number does not decrease.
How can I check that such a crash has happened on the server?
You should eventually receive the disconnect event, because socket.io has a heartbeat mechanism. I don't think there is any other way to detect a client crash. It does take some time though.
Heartbeat has been explained well here:
Advantage/disadvantage of using socketio heartbeats
When server calls disconnect(), the reason given to disconnect handler is: io server disconnect. And when server stops, the reason is: transport close.
So you can check this by adding a condition:
socket.on('disconnect', function(reason) {
if (reason === 'transport close'){
console.log('Server Crashed');
}
});

Can client know Node.js server has disconnected him

Environment
Server: Node.js
Client: Browser
Communication: Socket.io
I already handle on server side when a client disconnects. But I wonder, is it possible to handle a server disconnection on client side?
Said in other words,
suppose server enters exception state and shuts down, how can the client know this happened? Can I use the very same code
socket.on('disconnect', function() {...});
on client?
Appreciate the help.
Things tried
To check if client is getting notified via
socket.on('disconnect', function() {...});
I throw the following exception in the server:
setTimeout(function () {
console.log('Throwing error now.');
throw new Error('User generated fault.');
}, 9000);
In client I have:
socket.on('disconnect',function(data){ console.log('Server disconnected you'); } );
But the log message in client never happens. ¿?
From the socket.io client docs:
Events
connect. Fired upon connecting.
disconnect. Fired upon a disconnection.
So yes, the client works in identical manner to the server.
Checkout other socket.io client-side events. https://github.com/Automattic/socket.io/wiki/exposed-events
Try to listen 'reconnect_failed' or 'error' instead of 'disconnect'.

Categories

Resources