简体   繁体   English

Socket.io发送消息到特定的socket.id无法正常工作?

[英]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. 我在使用node.js服务器的socket.io中有这个应用程序,我想为应用程序中连接的每个点更新点。 I keep a list of connected users by socket.id and secret in the clients array. 我在clients数组中按socket.id和secret保留了已连接用户的列表。 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 Socket.io版本: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? 如何使客户端对象通过分配套接字和point属性然后将其推送到客户端数组中呢?

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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