[node.js] Socket.IO-연결된 소켓 / 클라이언트 목록은 어떻게 얻습니까?

현재 연결된 모든 소켓 / 클라이언트 목록을 얻으려고합니다.

io.sockets 불행히도 배열을 반환하지 않습니다.

배열을 사용하여 내 목록을 유지할 수는 있지만 이것이 두 가지 이유로 최적의 솔루션이라고 생각하지 않습니다.

  1. 여분. Socket.IO는 이미이 목록의 사본을 유지합니다.

  2. Socket.IO는 클라이언트 (예 :)에 대한 임의의 필드 값을 설정하는 방법을 제공 socket.set('nickname', 'superman')하므로 내 자신의 목록을 유지하려면 이러한 변경 사항을 따라야합니다.

도움?



답변

Socket.IO 0.7에서는 clients네임 스페이스에 대한 메소드가 있으며 연결된 모든 소켓의 배열을 반환합니다.

네임 스페이스가없는 API :

var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`

네임 스페이스

var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`

이것이 미래의 누군가를 돕기를 바랍니다.

참고 : 이 솔루션 은 1.0 이전 버전 에서만 작동합니다


업데이트 2020 년 3 월 6 일

1.x 이상에서이 링크를 참조하십시오 : socket.io의 대화방에 몇 명의 사람이 있는지 확인


답변

Socket.io 1.4

Object.keys(io.sockets.sockets); 연결된 모든 소켓을 제공합니다.

Socket.io 1.0
socket.io 1.0부터 실제 허용되는 답변은 더 이상 유효하지 않습니다. 그래서 임시 수정으로 사용하는 작은 기능을 만들었습니다.

function findClientsSocket(roomId, namespace) {
    var res = []
    // the default namespace is "/"
    , ns = io.of(namespace ||"/");

    if (ns) {
        for (var id in ns.connected) {
            if(roomId) {
                var index = ns.connected[id].rooms.indexOf(roomId);
                if(index !== -1) {
                    res.push(ns.connected[id]);
                }
            } else {
                res.push(ns.connected[id]);
            }
        }
    }
    return res;
}

네임 스페이스없는 API 가됩니다.

// var clients = io.sockets.clients();
// becomes : 
var clients = findClientsSocket();

// var clients = io.sockets.clients('room');
// all users from room `room`
// becomes
var clients = findClientsSocket('room');

네임 스페이스에 대한 API 는 다음과 같습니다.

// var clients = io.of('/chat').clients();
// becomes
var clients = findClientsSocket(null, '/chat');

// var clients = io.of('/chat').clients('room');
// all users from room `room`
// becomes
var clients = findClientsSocket('room', '/chat');

또한이 관련 질문을 참조하십시오 . 여기서 주어진 방의 소켓을 반환하는 함수를 제공합니다.

function findClientsSocketByRoomId(roomId) {
var res = []
, room = io.sockets.adapter.rooms[roomId];
if (room) {
    for (var id in room) {
    res.push(io.sockets.adapter.nsp.connected[id]);
    }
}
return res;
}

Socket.io 0.7

네임 스페이스없는 API :

var clients = io.sockets.clients();
var clients = io.sockets.clients('room'); // all users from room `room`

대한 네임 스페이스

var clients = io.of('/chat').clients();
var clients = io.of('/chat').clients('room'); // all users from room `room`

참고 : socket.io API가 깨지기 쉽고 일부 솔루션은 구현 세부 사항에 의존하기 때문에 클라이언트를 직접 추적해야 할 수도 있습니다.

var clients = [];

io.sockets.on('connect', function(client) {
    clients.push(client); 

    client.on('disconnect', function() {
        clients.splice(clients.indexOf(client), 1);
    });
});


답변

socket.io 1.0 이후에는 사용할 수 없습니다

io.sockets.clients();
or
io.sockets.clients('room'); 

더 이상 대신 다음을 사용할 수 있습니다

var clients_in_the_room = io.sockets.adapter.rooms[roomId];
for (var clientId in clients_in_the_room ) {
  console.log('client: %s', clientId); //Seeing is believing 
  var client_socket = io.sockets.connected[clientId];//Do whatever you want with this
}


답변

Socket.IO 1.x 사용 :

연결된 클라이언트의 배열을 가져옵니다.

io.engine === io.eio // => true
Object.keys(io.engine.clients) // => [ 'US8AxrUrrDF_G7ZUAAAA', 'Ov2Ca24Olkhf2NHbAAAB' ]
Object.keys(io.eio.clients)    // => [ 'US8AxrUrrDF_G7ZUAAAA', 'Ov2Ca24Olkhf2NHbAAAB' ]

연결된 클라이언트 수를 확보하십시오.

io.engine.clientsCount // => 2
io.eio.clientsCount    // => 2


답변

socket.io 1.3에서 매우 간단합니다.

io.sockets.sockets-연결된 소켓 객체를 포함하는 배열입니다. 각 소켓에 사용자 이름을 저장 한 경우 다음을 수행 할 수 있습니다.

io.sockets.sockets.map(function(e) {
    return e.username;
})

팔. 연결된 모든 사용자의 이름이 있습니다.


답변

나는 오늘이 고통을 겪었다. Socket.io는 API에 대한 적절한 문서를 만들 수 있으면 훨씬 더 좋습니다.

어쨌든, 나는 io.sockets를 살펴 보았고 우리가 사용할 수있는 많은 옵션을 발견했습니다.

io.sockets.connected //Return {socket_1_id: {}, socket_2_id: {}} . This is the most convenient one, since you can just refer to io.sockets.connected[id] then do common things like emit()
io.sockets.sockets //Returns [{socket_1}, {socket_2}, ....]. Can refer to socket_i.id to distinguish
io.sockets.adapter.sids //Return {socket_1_id: {}, socket_2_id: {}} . Looks similar to the first one but the object is not actually the socket, just the information.

// Not directly helps but still relevant
io.sockets.adapter.rooms //Returns {room_1_id: {}, room_2_id: {}}
io.sockets.server.eio.clients //Return client sockets
io.sockets.server.eio.clientsCount //Return number of connected clients

또한 네임 스페이스와 함께 socket.io를 사용하는 경우 io.sockets가 객체 대신 배열이되므로 위의 메소드가 중단됩니다. 해결하려면 io.sockets를 io로 바꾸십시오 (예 : io.sockets.connected는 io.connected, io.sockets.adapter.rooms는 io.adapter.rooms …)

socket.io 1.3.5에서 테스트


답변

버전 +2.0

버전 +2.0에서는 쿼리하는 네임 스페이스 / 룸 / 노드를 지정합니다.

브로드 캐스트와 마찬가지로 기본값은 기본 네임 스페이스 ( ‘/’)의 모든 클라이언트입니다.

const io = require('socket.io')();
io.clients((error, clients) => {
      if (error) throw error;
      console.log(clients); // => [6em3d4TJP8Et9EMNAAAA, G5p55dHhGgUnLUctAAAB]
});

특정 네임 스페이스에 연결된 클라이언트 ID 목록을 가져옵니다 (해당되는 경우 모든 노드에서).

const io = require('socket.io')();
io.of('/chat').clients((error, clients) => {
     if (error) throw error;
     console.log(clients); // => [PZDoMHjiu8PYfRiKAAAF, Anw2LatarvGVVXEIAAAD]
});

네임 스페이스의 방에있는 모든 클라이언트를 가져 오는 예 :

const io = require('socket.io')();
io.of('/chat').in('general').clients((error, clients) => {
      if (error) throw error;
      console.log(clients); // => [Anw2LatarvGVVXEIAAAD] 
});

이것은 공식 문서입니다. Socket.IO Server-API