How to get all the sockets connected to Socket.io

不羁岁月 提交于 2020-01-12 08:51:47

问题


I did some search here and found this answer

// list all connected sockets
    var list = io.sockets.sockets;
    console.log("Connected sockets:");
    list.forEach(function(s) {
        console.log("    socket.id = ", s.id);
    });

But because io.sockets.sockets; that mentioned there is NOT an array it doesn't work.so i have 2 questions :

a)How can i access to all sockets connected?

b)How can i access to sockets connected to specific room?

Cheers

PS:this question is asked before but those questions are out dated.


回答1:


In latest version of socket.io (1.4.5) you'l have to do

Object.keys(io.sockets.sockets);

This returns an array containing id's of sockets connected and you can apply forEach on it.

Object.keys(io.sockets.sockets).forEach(function(id) {
    console.log("ID:",id)  // socketId
})

Ok now for the B part, for getting array of socketids off sockets connected to a room use

Object.keys(io.sockets.adapter.rooms["ROOM_NAME"].sockets) //returns array of socketId's


来源:https://stackoverflow.com/questions/35249770/how-to-get-all-the-sockets-connected-to-socket-io

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!