Iterate over sockets in socket.io v1? “…has no met

2019-06-27 03:59发布

Before I was able to write something like this:

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

Now, I cannot and I get the error Object #<Namespace> has no method 'clients'

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

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

Here's an example

setInterval(function(){
    io.sockets.clients().forEach(function (socket) { 
        socket.emit('newMessage',someCalculations());
    });
},1000);

4条回答
叼着烟拽天下
2楼-- · 2019-06-27 04:33

I had got the same problem. Try using:

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

Hope it helps

查看更多
看我几分像从前
3楼-- · 2019-06-27 04:38

This is my current solution:

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

setInterval(function(){
    socketList.forEach(function(){
        socket.emit('newMessage',someCalculations());
    });
},1000);
查看更多
祖国的老花朵
4楼-- · 2019-06-27 04:44

If the info about all the connected sockets has to be send to a single socket then

    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)
    }
查看更多
叼着烟拽天下
5楼-- · 2019-06-27 04:50

If you want find out each 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.clients is a hash. The key is socket id and the value contain some useful info. e.g. request. If you use passport.socketio. You can get authed user from that place.

查看更多
登录 后发表回答