2012-01-03 39 views
1

我正在實施一個node.js服務器,它使用socket.io(版本:0.8.7)管理用戶之間的雙向連接。我使用一個存儲尚未有聊天夥伴的用戶的數組。當用戶請求新的合作伙伴時,應用程序將挑選該陣列中的用戶,然後檢查用戶是否仍然連接。這是我的問題:如何獲取用戶的套接字客戶端?

即使用戶仍然連接,我無法爲用戶獲取套接字客戶端。下面是我的代碼片段:

// An array of users that do not have a chat partner 
var soloUsers = []; 

var io = sio.listen(app); 

io.sockets.on('connection', function (socket) { 


    socket.on('sessionStart', function (message) 
    {  
     // Parse the incoming event 
     switch (message.event) { 

      // User requested initialization data 
      case 'initial': 
       ... 

     // User requested next partner 
     case 'next': 

     // Create a "user" data object for me 
     var me = { 
      sessionId: message.data.sessionId, 
      clientId: socket.sessionid 
     }; 

     var partner; 
     var partnerClient; 

     // Look for a user to partner with in the list of solo users 
     for (var i = 0; i < soloUsers.length; i++) 
     { 
      var tmpUser = soloUsers[i]; 

      // Make sure our last partner is not our new partner 
      if (socket.partner != tmpUser) 
      { 
       // Get the socket client for this user 
       partnerClient = io.sockets.clientsIndex[tmpUser.clientId]; 

       // Remove the partner we found from the list of solo users 
       soloUsers.splice(i, 1); 

       // If the user we found exists... 
       if (partnerClient) 
       { 
        // Set as our partner and quit the loop today 
        partner = tmpUser; 
        break; 
       } 
      } 
     } 

     ... 

我得到以下錯誤:

partnerClient = io.sockets.clientsIndex[clientId]; 
            ^
TypeError: Cannot read property 'undefined' of undefined 

我做的clientId的輸出(執行console.log),它肯定是indefined。此外,我認爲API可能在socket.io版本0.8中發生了變化,您不能再使用「clientsIndex」方法。有誰知道更換?

謝謝!

+0

您試圖用partnerClient實現的目標是什麼? – alessioalex 2012-01-03 21:55:48

+0

我想確保合作伙伴在將其分配給用戶之前仍處於連接狀態。 – 2012-01-03 22:01:29

+0

我在編輯帖子時添加了一個答案。順便說一下,循環遍歷一系列客戶端並不是那麼好,想象一下,如果您有10,000個客戶端,那麼這將會有多慢。這會阻止Node.js事件循環。 – alessioalex 2012-01-03 22:04:35

回答

7

要做的最好的事情是跟蹤對象中連接的客戶端。以下是我會做到這一點:

var clients = {}; 

io.sockets.on('connection', function (socket) { 
    // remember the client by associating the socket.id with the socket 
    clients[socket.id] = socket; 
    socket.on('sessionStart', function (message) { 
    // get the socket.id of the partner on each message 
    var partner = message.from; 
    if (clients[partner]) { 
     // check if the partner exists and send a message to the user 
     clients[socket.id].emit('message', { from: partner, msg: message }); 
    } 
    } 

    socket.on('disconnect', function() { 
    delete clients[socket.id]; // delete the client from the list 
    }); 
} 

注:在實際生產應用中,你通常會檢查會話數據,並且每個客戶端提供用戶名和socket.id關聯。