使用socket io将数据发送给特定用户

时间:2017-04-27 02:22:38

标签: javascript node.js socket.io

我有一个节点js服务器,它使用socket.io向用户发送数据。到目前为止,我可以向请求它的用户或所有用户发送数据。但我想知道一种方法将数据发送给其他人请求的特定用户。在这种情况下,它是一个可以托管游戏的网站。因此,当另一个用户想要加入时,我想将数据发送给托管该游戏的人,告诉他们该用户想要加入。这是我的代码

exports.Server = Server = function()
{
this.userId = 1;
this.userName = "Guest";
};

Server.prototype.initialise = function(port)
{
//Create the server using the express module
this.server = http.createServer(app);

//Declare the 'public' folder and its contents public
app.use(express.static('public'));  

//Listen to any incoming connections on the declared port and start using websockets
this.server.listen(port);
this.startSockets();
this.em = new events();

consoleLog('SERVER', 'Running on port: ' + port);
};

Server.prototype.startSockets = function()
{
//When a user connects to the server on the 'game' socket
this.socket = io.listen(this.server);

this.socket.of('game').on('connection', function(user)
    {
        //Set their usedId and username
        user.userId = this.userId;
        user.userName = this.userName + " " + this.userId;

        //Increment the user id by 1 so each user with get a unique id
        this.userId++;

        //Send a response back to the client with the assigned username and user id and initialise them
        user.emit('response', user.userId, user.userName);
        this.em.emit('initialiseUser', user.userId, user.userName);

        //Tell the server to log the user that has just connected
        consoleLog('SERVER', user.userName + ' has connected. ID: ' + user.userId)

        //Server listeners from the client

        //If the user wants to host a game, take the game settings they requested
        user.on('hostGame', function(boardSize, gameMode, gameNote)
            {       
                //Tell the app to request a new hosted game with the users information and settings
                this.em.emit('hostGame', user.userId, user.userName, boardSize, gameMode, gameNote);
            }
            .bind(this));

        //If the user wants to cancel the game they are hosting
        user.on('cancelHostGame', function()
            {   
                //Tell the app to request to cancel their game passing in the users information
                this.em.emit('cancelHostGame', user.userId, user.userName);
            }
            .bind(this));

        user.on('joinGame', function(user.id, user.userName, opponentId)
            {                       
                //Need to tell the user with the opponent Id, that the user.id wants to join
            }
            .bind(this));

        //When a user disconnects
        user.on('disconnect', function()
            {   
                //Tell the app to request to cancel the game the user was hosting
                this.em.emit('cancelHostGame', user.userId, user.userName);

                //Tell the server who disconnected
                consoleLog('SERVER', user.userName + ' has disconnected. ID: ' + user.userId)
            }
            .bind(this));
    }
    .bind(this));

};

function updateGamesList(socket, hostedGames)
{
//Emit the updateGameList function on the client and pass through the array of games being hosted
socket.socket.of('game').emit('updateGameList', hostedGames);
};

所以你可以看到当用户点击加入游戏时,它会传递托管他们想要加入的游戏的对手的id。如果我使用user.emit,它将转到加入的人,如果我这样做,则会发送给网站上的每个用户。我如何将它指向具有该特定ID的用户?

1 个答案:

答案 0 :(得分:0)

要向游戏主机发送确认,首先必须管理包含所创建的总游戏的对象,并且对象的每个值将包含一个数组,其中将有用户对象连接到游戏,因此该对象结构将看起来等,

var object={};
object={ game1 : [object-user1,object-user2,object-user3],
         game2 : [object-user1,object-user2,object-user3],
         game3 : [object-user1,object-user2,object-user3]
};

现在,当用户创建房间时,其对象将存储在房间下的对象中,这可以按照下面的方式完成

var object={};
io.on('connection', function(user){
    user.on('createroom',function(game){
        var array=[];
        array[0]=user;
        object[game]=array
        socket.join(data[0]);
        socket.emit('createres', data[0]);
    });
});

现在你有一个包含游戏的对象和相应的数组,其中包含用户连接游戏的列表,现在如果你想发送确认给你可以做的游戏主机,如下所示,

user.on('joingame',function(game){
    data.game=game;
    data.user=user;
    object[game][0].emit("confirmjoin",data);
});

上面的代码是针对服务器端的,在上面的代码中我们向创建游戏的用户发送确认,这里对象[game] [0]将返回特定游戏的数组的第一个元素,所以我们可以使用该值调用客户端;

这是客户端代码,

user.on('confirmjoin',function(data){

    if(//allow user to join){
        user.emit('allowtojoin',data);
    }
});

上面的代码是针对客户端的,在上面的代码中如果游戏主机想要允许加入用户,它将检查条件并且它将向服务器发送“allowjoin”发送用户对象,

这是服务器端代码,它将监听加入游戏,

user.on('allowjoin',function(data){
    data.user.join(data.game);
});

现在你的server.js文件会包含类似的内容

var object={};
io.on('connection', function(user){
    user.on('createroom',function(game){
        var array=[];
        array[0]=user;
        object[game]=array
        socket.join(data[0]);
        socket.emit('createres', data[0]);
    });
    user.on('joingame',function(game){
        data.game=game;
        data.user=user;
        object[game][0].emit("confirmjoin",data);
    });
    user.on('allowjoin',function(data){
        data.user.join(data.game);
    });
});

希望这会有所帮助。!

相关问题