无法使用本地主机上的node.js向不在线的用户发送消息

Unable to send messages to who are not online using node.js on my localhost

本文关键字:在线 用户 消息 js node 主机      更新时间:2023-09-26

我已经用socket.io启动并运行了节点。我可以向在我的服务器上在线的人(他们的套接字连接打开)发送消息。但当我尝试发送给多个人,至少有一个人离线时,它不会通过。如果所有人都在线,它就会通过。

关于如何解决这个问题,有什么帮助吗?

client.on('message_from_client',function(data){
    for(var i=0;i<data.length;i++){
        if(data[i].message_to!=''){
            client.emit("update_message_from_server", data[i]);
            if(data[i].message_to != client.username){
                var message_to = data[i].message_to;
                var array =data[i];
                redisClient.SISMEMBER('online',message_to,function(err,reply){
                    if(reply!=0){
                        redisClient.get(message_to,function(err,reply2){
                            if(reply2!=null){
                                io.sockets.sockets[reply2].emit("update_message_from_server",array );
                            }
                        });
                    }else{
                        console.log("Offline");
                    }
                });
            }
        }else{
                client.emit("update_message_from_server", data[i]);
        }   
    }
});

data是一个JSON对象。如果我有任何数据[i].message_to处于脱机状态,我只能将其发送到客户端,而不能发送到其他套接字。如果我所有的条目都在线,我可以将其发送到客户端和其他套接字

我找到了其他方法来完成

client.on('message_from_client',function(data){
        alldata = data.data;
        console.log(alldata);
        alldata = JSON.parse(alldata);
        alldata.forEach(function(data){
            if(data.message_to!=''){
                client.emit("update_message_from_server", data);
                if(data.message_to != client.username){
                    redisClient.SISMEMBER('online',data.message_to,function(err,reply){
                        if(reply!=0){
                            redisClient.get(data.message_to,function(err,reply2){
                                if(reply2!=null){
                                    io.sockets.sockets[reply2].emit("update_message_from_server",data );
                                }
                            });
                        }else{
                            console.log("Offline");
                        }
                    });
                }
            }else{
                    client.emit("update_message_from_server", data);
            }   
        });
    });