发送客户端其他玩家的得分?socket . io

Send client other players score? Socket.io

本文关键字:socket io 客户端 其他 玩家      更新时间:2023-09-26

我有一种情况,我不确定如何向其他客户发送他们竞争对手的当前分数。

例如:

当玩家1点击时,我希望它能告诉玩家2玩家1在客户端的得分。

    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发送分数。但我不确定最好的方法。

最好的方法是创建一个包含所有连接的对象,每次用户连接/断开连接时更新该对象。我看到你已经有了它们的id的userid列表,所以,如果你的对象被称为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];
    }
}