简体   繁体   中英

Socket.io sending message to specific socket.id not working?

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

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;

Replace the

io.sockets.connected[socketID].emit('update points', pontos);   

with this

socket.broadcast.to(socketID).emit('update points', pontos);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM