Detect Websocket close connection when the users close browser? - javascript

I am using HTML5 websocket and nodejs in my project to create a simple chat.
Everything works as it should so far.
However, I need to figure out how to detect if the the users that are connected, lost connection somehow and in particular, if they close their browser etc.
I tried the following code.
I can successfully connect like this:
wss.on('connection', function(ws, req) {
//do my stuff here/////
console.log('connection started');
});
However, i cannot see anything in the console when i disconnect by closing the browser.
I use this code to detect connection close:
wss.on('closed', function(ws) {
console.log('connection closed');
});
Could someone please let me know if I am missing something and or doing something wrong?
Thanks in advance.
edit:
This seems to work:
ws.on("close", function() {
console.log("closed");
});

As discussed in this post, the default Websocket implementation doesn't have a way to detect network disconnects, only an intentional disconnect from the user. I recommend that you try to use Socket.IO, as it will do similar what you're looking for, and can detect disconnects. Here's an example:
var io = require('socket.io')(80);
io.on('connection', function (socket) {
socket.on('disconnect', () => {
console.log('User disconnected.')
});
The one disadvantage to using Socket.IO is that you'll have to use a JS library on your client instead of using raw WebSockets, but you'll gain the ability to see when a client disconnects.

Related

Detect client's disconnection WebSocket

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
});
});

How to detect when the socket is opened on client?

While using socket.io on the client browser side, how can I detect when the socket actually opened? Along with all the other basic default messages (such as errors and disconnection)
I am referring to how the default WebSocket API has websocket.onopen = function(){}, .onerror and .onclose.
Using socket.on("connect", function(){some code here}) and socket.on("connection") does nothing.
you can have a look at:
Docs of SocketIO
because it is such an easy question im adding the message below.
it isnt hard to find the solution to this, just search and you will find what you need.
It is wrong to (be lazy) and ask your question on a platform such as stackoverflow for all you programming information. it is always better to look for docs and examples. because you learn more when you look it up yourself or find it out yourself.
of course you can ask questions when you are really stuck and you cant move forward and you know for sure it takes to long otherwise.
if you want the easy way here is the solution:
http://socket.io/docs/#sending-and-receiving-events
http://socket.io/docs/client-api/
use "disconnect", when disconnect event is triggered on times you dont expect, its is clearly a connection drop.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
Ok, so before I tried this
socket.on("connect", function(){
alert("socket open test")
})
and it didn't work but and now I tried again and somehow for some reason it does, sorry for the confusion and waste of time.

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'.

Using socket.io (node.js) server with Cordova App in Visual Studio

I'm currently testing a theory. I have VS2013 and have installed Apache Cordova and Node.js project libraries. I have created NodeJS+Socket.IO websites before using the native command line methods, mostly using guides so my understanding of "how things work" is on the basic side. Below is a picture of the VS Project I've created:
Basically I want to be able to use socket.io to communicate data between the two projects. I've done a fair bit of research on Google and on here and can't find anything specific, how could this be achieved?
I have seen this question which tells me this could potentially be achieved, but that is natively Android and not Cordova.
It also may be that using NodeJS isn't the best option. Ultimately I'm wanting to be able to communicate with an existing (very large) .Net application so I would be interested to know if there's a better way of doing this (skipping the NodeJS layer entirely?).
Thanks for your time
UPDATE
Something I'm trying, but getting connection error:
Server Side
var http = require('http');
var server = http.createServer();
var io = require('socket.io')(server);
server.listen(5022, function () {
console.log('listening on *:5022');
});
io.sockets.on('connection', function (socket) {
console.log('socket connected');
socket.on('disconnect', function () {
console.log('socket disconnected');
});
socket.emit('text', 'wow. such event. very real time.');
});
App
document.addEventListener('deviceready',
function() {
onDeviceReady.bind(this);
console.log('Device is Ready')
var socket = io.connect('http://MyDomain:5022');
socket.on('connect', function () {
socket.on('text', function (text) {
console.log(text);
});
});
},
false);
I get the Device is Ready message, but I get this message:
Failed to load resource: net::ERR_CONNECTION_REFUSED
File: xhr_proxy, Line: 0, Column: 0
I created a new question on here. The code I created was fine, it was just the debug method I was using (Ripple) which was preventing CORS in the browser.

Memory leaks using socket.io

I've found that sockets are not fully destroyed in socket io server side when manually disconnecting them. I've found this topic on github useful. While I'm looking for some variable-links that prevent GC from cleaning sockets, I'm asking a question here.
If anyone here encountered the same problem, this would be much help.
the code that does not work:
socket.on('disconnect', function(){
socket.removeAllListeners();
});
///...................
socket.disconnect();
Workaround that, however, uses restricted library fields:
delete io.sockets[url];
io.j = [];
actually, this is working as intended, when you disconnect a socket you simply state you're not expecting to receive any more data from that socket right now, to actually destroy the socket you basically do the delete socket action. Use this on the disconnect event, ie:
socket.on('disconnect', function(){
delete socket;
})
you can also do this on the io.sockets.sockets Object on an external function:
function deleteSocket(socketID){
delete io.sockets.sockets[socketID];
}

Categories

Resources