2016-05-13 3 views
1

Ich benutze eine neuere Version von socket.io und ich kann nicht herausfinden, wie Sie eine Liste von Socket Objekte bekommen. Ich habe einige Tutorials und Antworten Stackoverflow wie diese gefolgt:Wie bekomme ich eine Liste von verbundenen Socket-Objekten (nicht Socket-IDs) in socket.io v1 +?

How to get all the sockets connected to Socket.io

Ich habe auch an der Dokumentation gesucht, aber es nicht viel geholfen hat. Alle Posts, die ich gefunden habe, erklären, wie man socketIds bekommt, aber ich brauche die Sockets selbst, damit ich nur bestimmte Sockets ausgeben kann.

Wie also bekommen Sie die eigentlichen Sockets selbst, oder ist das in neueren Socket-Versionen nicht mehr möglich?

Antwort

2

Sie können ein paar Möglichkeiten:

// An object with socket.id as property and socket object as value 
// You could iterate this with for/in or use `Object.keys()` to get the ids 
// and then access each socket by id 
// io.sockets.connected 

var ids = Object.keys(io.sockets.connected); 
ids.forEach(function(id) { 
    var socket = io.sockets.connected[id]; 
    // do something with socket here 

}); 

// an array of sockets which you can iterate directly as an array. 
// io.sockets.sockets 

io.sockets.sockets.forEach(function(socket) { 
    // do something with socket here 

}); 

Sie können auch separat Namespaces zugreifen:

// array of sockets in this namespace 
io.nsps['/'].sockets 

// map of socket ids in this namespace 
io.nsps['/'].connected 
Verwandte Themen