如果客户端使用 Web 套接字关闭互联网,我想检测客户端连接。我的代码是:
//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())但没有奏效。