Reputation: 381
I have this app in socket.io using node.js server and I want to update the points for every one connected in the app. I keep a list of connected users by socket.id and secret in the clients array. And I tried like this but the points won't update. Can anyone tell me what's wrong?
function updatePoints(){
points = [];
pool.getConnection(function(err, connection) {
connection.query("SELECT * FROM `users`", function(error, rows) {
for (var i = 0; i < rows.length; i++) {
points.push({"secret" : rows[i].secret, "points" : rows[i].pontos});
}
for (var l = 0; l < points.length; l++) {
for (var p = 0; p < clients.length; p++) {
if(points[l].secret == clients[p].secret){
var socketID = clients[p].socket;
var pontos = points[l].points;
io.sockets.connected[socketID].emit('update points', pontos);
}
}
}
});
});
}
Socket.io version: 1.3.7
Upvotes: 0
Views: 1137
Reputation: 611
Replace the
io.sockets.connected[socketID].emit('update points', pontos);
with this
socket.broadcast.to(socketID).emit('update points', pontos);
Upvotes: 0
Reputation: 1031
How about make a client object theb assigning a socket and a point property then push it in a the clients array?
socketServer.on('connection', function(socket){
//make your query here
...
//make a client object
var client = {point: row.point, socket: socket};
clients[row.secret] = client;
});
then you can retrieve the client by:
//query...
....
clients[row.secret].socket.emit('something', function);
edit:
if you want to broadcast to connected clients then you can:
socketServer.emit('something', function);
if you want to broad to everyone except the one who emitted the broadcast. then you can:
clients[row.secret].broadcast.emit('something', function;
Upvotes: 1