Extract all socket objects in io.socket

I am looking to get all socket objects from io.sockets and iterate over each one.

Sort of:

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

Either I'm doing it wrong, or I'm missing something. Thoughts?

+6
source share
2 answers

Official method:

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

Or filter by room:

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

This is stated above, because the internal data structure of socket.io can always be changed and could potentially damage all your code with future updates. You are much less at risk when using this official method.

+14
source

This may or may not be documented, but it 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 join your application and check the contents of s .

+2
source

Source: https://habr.com/ru/post/900793/


All Articles