Iterate over sockets in socket.io v1? "... does not have a" clients "method"

Before I could write something like this:

io.sockets.clients().forEach(function (socket) { 
    socket.emit(signal,data);
});

Now I can’t and get an error Object #<Namespace> has no method 'clients'

Is there any other way to do this? This is with socket v1.0. (or 1.0.2, I think).

For this, I know what I can use io.emit(), but I would like to iterate over sockets and perform functions on them in a timer. I can reorganize everything into callbacks and set the timer to io.on(), but I think I will need to use links (I think javascript will make a copy of the object socketin this case instead of referencing it?)

Here is an example

setInterval(function(){
    io.sockets.clients().forEach(function (socket) { 
        socket.emit('newMessage',someCalculations());
    });
},1000);
+4
source share
4 answers

:

var socketList = new Array();
io.on('connection',function(socket){
    socketList.push(socket);
});

setInterval(function(){
    socketList.forEach(function(){
        socket.emit('newMessage',someCalculations());
    });
},1000);
+1

​​ ,

    for (var i in io.sockets.connected) {
        var s = io.sockets.connected[i];
        if (socket.id === s.id) {
           continue;
        }
        socket.emit('notify_user_state', s.notify_user_state_data)
    }
+2

I had the same problem. Try using:

io.sockets.emit('newMessage', someCalculations());

Hope this helps

+1
source

If you want to know all connected clients. You can get them from engine.io

for (var sid in io.engine.clients) {
  io.to(sid).emit('your message', data);
}

io.engine.clientsis a hash. The key is the socket identifier, and the value contains some useful information. for example request. If you use passport.socketio. You can get a lost user from this place.

+1
source

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


All Articles