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);
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)
}
I had got the same problem. Try using:
io.sockets.emit('newMessage', someCalculations());
Hope it helps
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);
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.