2013-11-25 63 views
0

我有一個問題:如何找到帶參數的插座。查找帶參數的插座

例如,當客戶端連接我添加到插座的一些參數:

socket.name = 'John'; 
socket.country = 'USA'; 
socket.age = 25; 


而如何尋找其中有一個國家China例如插座。

socket.on('search', function(country) { 
    // Give list of sockets were (socket.country) = country 
}); 

回答

0

保持插座的全局數組並將其過濾與filter

var socketList = []; 

io.sockets.on("connection", function(socket) { 
    // add socket to list on connection 
    socketList.push(socket); 

    // remove socket from list on disconnect 
    socket.on("disconnect", function() { 
     socketList.splice(socketList.indexOf(socket), 1); 
    }); 

    socket.on('search', function(country) { 
     // Give list of sockets where (socket.country) = country 
     var filteredList = socketList.filter(function(s) { 
      return s.country == country; 
     }); 
    }); 
}); 

如果你有插座的數量龐大且filter荷蘭國際集團在O(n)的時間過得很慢,你可以改變代碼保持O(1)訪問的查找表,這可能看起來像一個對象,其成員是插座的數組:

{ 
    "USA": [socket, socket, socket, ...], 
    "Canada": [socket, socket, ...], 
    ... 
} 

而且你訪問的每個列表與socketLookupTable[countryName]