发送客户其他玩家得分? Socket.io

时间:2016-07-04 01:25:38

标签: javascript jquery socket.io

我有一种情况,我不知道如何向其他客户发送竞争对手目前的分数。

例如:

当玩家1点击时我想要它然后告诉玩家2玩家一方在客户端的得分。

    userOne = userIDs[0];
    userTwo = userIDs[1];

    socket.on("player one", function(data) {
        console.log(data.pScore + "THIS IS WORKING");
        score = data.pScore;
        console.log("THIS IS PLAYER TWO" + data.pNameTwo);
        if (isInArray(data.pNameTwo,allUsers)) {
            console.log(users[socket.id].username);
        }
        socket.emit("player ones score", {p1Score: score});
    });

    socket.on("player two", function(data) {
        console.log(data.pScore + "THIS IS WORKING");
        score = data.pScore;
        socket.emit("player twos score", {p2Score: score});
    }); 

我打算只发送一个特定的用户ID来发送分数。但我不确定最好的方法。

1 个答案:

答案 0 :(得分:1)

这样做的最佳方法是让对象包含所有连接,每次用户连接/断开连接时都会更新。我看到你已经有了一个idID的userIDs列表,所以,如果你的对象名为userConnections,你的代码应该是......

userOne = userIDs[0];
userTwo = userIDs[1];

socket.on("player one", function(data) {
    console.log(data.pScore + "THIS IS WORKING");
    score = data.pScore;
    console.log("THIS IS PLAYER TWO" + data.pNameTwo);
    if (isInArray(data.pNameTwo,allUsers)) {
        console.log(users[socket.id].username);
    }
    userConnections[userTwo].emit("player ones score", {p1Score: score});
});

socket.on("player two", function(data) {
    console.log(data.pScore + "THIS IS WORKING");
    score = data.pScore;
    userConnections[userOne].emit("player twos score", {p2Score: score});
}); 

<强>更新

好的,我将展示如何初始化和管理userConnections。它是这样的(我只是猜测代码中的某些变量是如何被调用的,所以我可能会错误地命名一些)。

var userConnections = {}

io.on('connection', function(socket) {
    userConnections[socket.id] = socket;

    //socket.on('player one', function(data) { ... } );
    //socket.on('player two', function(data) { ... } );

    socket.on('disconnect') {
        delete userConnections[socket.id];
    }
}