node.js - 网络套接字 : cannot detect client connection on internet disconnect

标签 node.js sockets websocket npm socketrocket

如果客户端使用网络套接字关闭互联网,我想检测客户端连接。我的代码是:

 //Include util library
    var util = require('util');
    // Include underscore library
    var _ = require('underscore')._;
    //For websocket
var webSocketServer = new (require('ws')).Server({port: (process.env.PORT || 5000)}),
webSockets = {} // userID: webSocket

// CONNECT /:userID
// wscat -c ws://localhost:5000/1
webSocketServer.on('connection', function (webSocket) 
{
  var userID = webSocket.upgradeReq.url.substr(1);
  //console.log('User_id is ',userID);
  webSockets[userID] = webSocket
                   util.log('User_id: [' + userID + '] enter in connected users list of [ ' + Object.getOwnPropertyNames(webSockets)+' ]')
                   // Call function which check id exist in letswalkee DB table
                   check_userid(userID);


                   // Send msg like: [fromUserID, text]    [1, "Hello, World!"]
webSocket.on('message', function(message) {
util.log('Received from [' + userID + ']: ' + message)
var messageArray = JSON.parse(message)
                                    var toUserWebSocket = webSockets[messageArray[0]]
                                    if (toUserWebSocket) {
                                    util.log('Sent to [' + messageArray[0] + ']: ' + JSON.stringify(messageArray))
                                    messageArray[0] = userID
                                    toUserWebSocket.send(JSON.stringify(messageArray))
                                    }
                                    })

                   webSocket.on('close', function () 
                   {
                      delete webSockets[userID]
                      util.log('User_id Deleted from connected users: [ ' + userID+' ]');

                    })
webSocket.on('disconnect',function()
  {
   console.log('hello i am disconnected');  
  });
})

我使用了该代码 (webSocket.on('disconnect',function()) 但没有奏效。

最佳答案

WebSocket是基于TCP的,TCP使用FIN包来关闭连接。在突然失去互联网连接的情况下,WebSocket 服务器和手机都不知道已经死掉的 TCP 连接,因为没有发送 FIN 数据包。

为了解决这个问题,TCP 有一个叫做keepalive 的机制。

我为解决这个问题所做的是调整 Linux 内核中的 TCP keepalive 设置,并调用 ws._socket.setKeepAlive(true)。

引用: https://github.com/websockets/ws/issues/353

关于node.js - 网络套接字 : cannot detect client connection on internet disconnect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25220006/

相关文章:

javascript - 什么可能导致socket.io服务时间过长?

node.js - socket.io - 传输关闭

Android 监听来自服务器套接字的消息

java - 使用身份验证 cookie 打开 WebSocket 连接

node.js - Mongodb购物车,如何查看和更新​​库存

javascript - 超测错误 : expected '[]' response body, 得到 '[""]'

xml - 如何使用 Node 转换流将 XML 转换为 JSON

node.js - 如何仅使用firebase进行身份验证并使用nodejs作为后端?

Python客户端/服务器发送大尺寸文件

java - Socket和Thread,这段代码是做什么的?