Wal*_*jad 5 sockets websocket node.js npm socketrocket
如果客户端使用Web套接字关闭Internet,我想检测客户端连接。我的代码是:
//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');
});
})
Run Code Online (Sandbox Code Playgroud)
我使用了该代码(webSocket.on('disconnect',function()),但是没有用。
WebSocket是基于TCP的,TCP使用FIN数据包来关闭连接。在互联网连接突然丢失的情况下,WebSocket 服务器和手机都不会意识到 TCP 连接已经失效,因为没有发送 FIN 数据包。
为了解决这个问题,TCP 有一个称为 的机制keepalive。
我为解决这个问题所做的就是调整keepaliveLinux内核中的TCP设置,并调用ws._socket.setKeepAlive(true).
参考: https: //github.com/websockets/ws/issues/353
| 归档时间: |
|
| 查看次数: |
3456 次 |
| 最近记录: |