最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 3

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

发布评论

评论列表(0)

  1. 暂无评论