最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Retrieving all socket objects in io.socket - Stack Overflow

programmeradmin1浏览0评论

I'm looking to get all individuals socket objects out of io.sockets and iterate over each of them.

Something like:

for (socket in io.sockets.something()) {
   // do something with each socket
}

Either I'm doing this wrong or I must be missing something. Thoughts?

I'm looking to get all individuals socket objects out of io.sockets and iterate over each of them.

Something like:

for (socket in io.sockets.something()) {
   // do something with each socket
}

Either I'm doing this wrong or I must be missing something. Thoughts?

Share Improve this question edited Nov 4, 2011 at 18:26 josh3736 145k34 gold badges226 silver badges270 bronze badges asked Nov 4, 2011 at 17:22 David ChouinardDavid Chouinard 6,8368 gold badges46 silver badges64 bronze badges 2
  • So, what's the problem or the question? – thejh Commented Nov 4, 2011 at 17:26
  • I'm just curious, what would be the use case for this? – alessioalex Commented Nov 4, 2011 at 17:43
Add a comment  | 

3 Answers 3

Reset to default 15

The official method is:

io.sockets.clients().forEach(function (socket) { .. });

Or filter by rooms:

io.sockets.clients('roomname') .. same as above ..

This is advised over the suggestion above as socket.io's internal data structure could always be subject to change and potentially breaking all your code with future updates. You much less at a risk when you use this official method.

This may or may not be 'documented', but works:

for (var id in io.sockets.sockets) {
    var s = io.sockets.sockets[id];
    if (!s.disconnected) {
        // ...
        // for example, s.emit('event', { ... });
    }
}

Use io.sockets.clients():

io.sockets.clients().forEach(function(s) {
    // ...
    // for example, s.emit('event', { ... });
});

You can use the excellent node-inspector to attach to your app and inspect the contents of s.

Get all sockets with no room:

for (let s of io.of('/').sockets) {
let socket = s[1];
socket.emit(...);}
发布评论

评论列表(0)

  1. 暂无评论