Socket使用Node.js发出ajax接收的数据

时间:2015-06-02 17:15:30

标签: javascript ajax node.js websocket socket.io

服务器端:我通过ajax接收用户列表,我试图通过套接字发出它,但只发送到同一个客户端。 像这样的东西

io.sockets.emit("users list", {users: users, me : req.me});//This work, but to all users

socket.emit("users list", {users: users, me : req.me}); //Im trying something like this

代码

//Receive user list
    app.post('/', function(request, response){
        response.setHeader('Access-Control-Allow-Origin', 'http://localhost'); //To allow response
        var req = JSON.parse(request.body.data);
        if(typeof req != "object") {
            response.send({status: false, msg: "Error on load user list"});
        } else {
            socket.id = req.me.id;
            req.users.data.forEach(function(user) {
                if(users[user.id] == null)
                    users[user.id] = user;
            });

            //io.sockets.emit("users list", {users: users, me : req.me});//This work, but to all users
            socket.emit("users list", {users: users, me : req.me}); //Im trying something like this
        }
        response.send({status: true, msg: ""});// echo the result back
    });

我也想知道是否有一些最好的方法来做到这一点......

1 个答案:

答案 0 :(得分:0)

您可以尝试将数据发送到特定套接字,如下所示:

io.sockets.socket(socket.id).emit(" users list",{users:users,me:req.me});