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");
});
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");
});
Share
Improve this question
edited Jun 16, 2018 at 16:00
william wolly
asked Jun 16, 2018 at 15:17
william wollywilliam wolly
3451 gold badge5 silver badges16 bronze badges
1 Answer
Reset to default 3As 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 remend 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.