2015-03-08 147 views
1

我有一個要求使用節點js處理從聊天應用程序斷開用戶。句柄瀏覽器刷新socket.io

我不知道如何處理告訴瀏覽器關閉和用戶刷新瀏覽器之間的區別。

client.on('disconnect', function() { 
     console.log('Disconnected'); 
     // run mysql code to remove user from logged in table 
}); 

我已經搜索了幾個小時並找不到解決方案。

這看起來很簡單,我認爲這是我使用的關鍵字。

有人能指出我如何處理這個問題的正確方向嗎?

在此先感謝。

回答

2

一種方法是生成一個隨機UID並將其保存到本地存儲。在客戶端連接之後,將此UID發送到服務器並檢查該UID是否作爲連接用戶存在。在服務器端,在斷開連接時設置超時時間,使用戶在從「用戶在線」數據中刪除其唯一UID之前15秒左右。

客戶:

// When the client starts, create the uid. 
localstorage.setItem('uUID', Math.random().toString(24) + new Date()); 

// Emit the UID right after connection 
socket.emit('userLogin', localstorage.getItem('uUID'); 

服務器:

var currentUIDS = []; 
var userIsConnected = true; 


io.sockets.on('connection', function (socket) { 
    var currentUID = null; 

    socket.on('userLogin', function (data) { 
     if (data !== null) { 
      if (currentUIDS.includes(data)) { 
       userIsConnected = true; 
     currentUID = data; 
      } 
     } 
    }); 

    socket.on('disconnect', function() { 
     userIsConnected = false; 
     setTimeout(function() { 
      if (!userIsConnected) currentUIDS.pop(currentUID); 
     }, 15000); 
    }); 
}); 
+0

這不符合工作因爲'currentUIDS'和'u serIsConnected'是全局變量,並不是特定於當前會話 – andreasonny83 2016-01-03 23:30:58

2

我有一個更好的解決方案來處理多個用戶:

var users = [], 
    users_connected = []; 

io.on('connection', function(socket) { 
    var uid = null; 

    // register the new user 
    socket.on('register', function (user_uid) { 
    if (users_connected.indexOf(user_uid) < 0) { 
     users_connected.push(user_uid); 
    } 

    if (users.indexOf(user_uid) < 0) { 
     console.log('New user connected: ' + user_uid); 
     users.push(user_uid); 

     // notify other clients that a new user has joined 
     socket.broadcast.emit('user:join', { 
     name: user_uid, 
     users: users_connected.length 
     }); 
    } 

    uid = user_uid; 
    }); 

    // clean up when a user leaves, and broadcast it to other users 
    socket.on('disconnect', function() { 
    users_connected.splice(users_connected.indexOf(uid), 1); 

    setTimeout(function() { 
     if (users_connected.indexOf(uid) < 0) { 
     socket.broadcast.emit('user:left', { 
      name: uid 
     }); 

     var index = users.indexOf(uid); 
     users.splice(index, 1); 
     } 
    }, 3000); 
    }); 

});