【问题标题】:Wait on client responses to run code socket.io?等待客户端响应运行代码 socket.io?
【发布时间】:2016-07-03 10:14:59
【问题描述】:

我有一些代码,只有在两个客户都输入答案后才尝试运行。这些是函数finish 和datarequest();。

目前我有它,它可以正确等待两个响应,并且不会在一个客户回答后立即发出。问题在于它没有到达我的 if 语句。

有没有办法 ++ nrecieved++;根据客户给出的答案类型。 IE。两个错误答案,两个正确答案还是一个?基本上是让它运行nrecieved++;同时基于两个客户的响应?

var nrecieved = 0;
var responses = {}; // Socket id to response

function finish(){
   // Loop through users in game and send them their responses
   for(var id in responses){
        if(responses.hasOwnProperty(id)){
             // Send the response
             io.to(id).emit('updatePlayer', responses[id]);
        }
   }
}

socket.on('playerCorrect', function (data) {
    nrecieved++;
    responses[socket.id] = data;
    answerValidation(nrecieved);
});    

socket.on('playerWrong', function (data) {
    nrecieved++;
    responses[socket.id] = data;
    answerValidation(nrecieved);
}); 

console.log(nrecieved);
function answerValidation(value) {
    nrecieved = value + value;
    console.log(value);
    if(nrecieved == 2){
        finish();
        dataRequest();
    } 
}

编辑:

包含的 pastebin:http://pastebin.com/y6akQ6Sh

客户端:

// On click of a answer button check if it is the correct answer if it is tell the server
$(document).on('click', '.answerButton' , function(){

    function answerChecker(element){
        if(element == gaPosition) {
            correctAnswer();
        }
        else {
            console.log("Incorrect!");
            incorrectAnswer();
        }
    }

    var clickedButton = $(this).data('button');
    console.log(clickedButton);
    answerChecker(clickedButton);

}); 

function buttonRemover() {
    $(".buttonContainer").removeClass("fadeInRightBig");
    $(".buttonContainer").addClass("fadeOutRightBig");
    setTimeout(function() {
        $(".buttonContainer").remove(); 
    }, 500);
}

// Random number function    
function randomIntFromInterval(min,max){
    return Math.floor(Math.random()*(max-min+1)+min);
}

// Check if correct + send to server
function correctAnswer() {
    var correct = true;
    socket.emit('playerCorrect', {answer: correct});
    console.log(correct);
    buttonRemover();
}

// Check if wrong + send to server
function incorrectAnswer () {
    var wrong   = false;
    socket.emit('playerWrong', {answer: wrong});
    buttonRemover();
}

socket.on ('updatePlayer', function (data) {
    if (data.answer === true) {
        console.log ('Player got it right! ' + data.answer);
    }else if (data.answer === false) {
        console.log ('Player got it wrong! ' + data.answer);
    }

});

【问题讨论】:

    标签: javascript jquery socket.io


    【解决方案1】:

    尝试创建自己的对象来存储用户及其套接字和答案。

    以下是您的存储方式的示例:

    var socketStorage = {
      roomname : {
    
       some-socketid : {  // the socket id from socket.id
    
           username : "username",     // the username of the user
           socket : socket,       // the socket of the user
           currQuestion : {     // an object representing the current question
              answered : false,
              answer : false 
           },
           allQuestionsAnswers : [ true, true, true ] // an array of answers
    
       },
    
       some-socketid : {  
        // the socket id from socket.id
           username : "otherusername",     
           socket : socket,      
           currQuestion : {   
              answered : false,
              answer : false 
           },
           allQuestionsAnswers : [ true, true, false ] 
    
       },
    
      }
    };
    

    这是你如何使用这个对象:

    var socketStorage = {};
    
    io.sockets.on("connection",function(socket){
    
     var roomName = "gamelobby"; // ideally generate a unique room where 2    sockets would join
    
    
     socketStorage[roomName] = {};
    
     socketStorage[roomName][socket.id] = {
          username : "username",     
          socket : socket,      
          currQuestion : {   
                  answered : false,
                  answer : false 
          },
          allQuestionsAnswers : [] 
     };
    
    
    })
    

    理想情况下,让用户向您发送他的信息(例如用户名),例如:

     socket.emit("setusername", {username:"my-awesome-username"});
    

    并在服务器上以这种方式在存储中设置用户名:

    socket.on("setusername", function(msg){
    
    
      socketStorage[roomName][socket.id].username = msg.usename;
    
    })
    

    这是一个简单的工作示例:

    客户端:

    socket.on("connect",function(){
    
        // Joining the game
        socket.emit('joingame', {username:"foobar"});
    
        $(document).on('click', '.answerButton' , function(){
    
        function answerChecker(element){
          if(element == gaPosition) {
            correctAnswer();
          }
          else {
            console.log("Incorrect!");
            incorrectAnswer();
          }
        }
    
        var clickedButton = $(this).data('button');
        console.log(clickedButton);
        answerChecker(clickedButton);
    
       }); 
    
      function correctAnswer() {
        var correct = true;
        socket.emit('playercorrect', {answer: true});
        console.log(correct);
        buttonRemover();
      }
    
      // Check if wrong + send to server
      function incorrectAnswer () {
        var wrong   = false;
        socket.emit('playerwrong', {answer: false});
        buttonRemover();
      }
    
        socket.on("updateplayer", function(data){
            if (data.answer === true) {
             console.log ('Player got it right! ' + data.answer);
            } else if (data.answer === false) {
             console.log ('Player got it wrong! ' + data.answer);
            }
        })
    
       socket.on("gamefinished", function(data){
          console.log(data.message);
       });
    
    
    })
    

    还有服务器端:

    var users =  {}, validQuestions = [], validCurrQuestion = [];
    
    io.sockets.on('connection', function(socket){
    
        socket.on("joingame", function(msg){
    
                console.log("joining game");
    
                users[socket.id] = {responses:[],currQuestion: {answered:false,answer:null}};
    
                socket.on("playercorrect",function(msg){
    
                    users[socket.id].currQuestion.answered = true:
                    users[socket.id].currQuestion.answer = true: 
                    users[socket.id].responses.push(msg.answer);
    
                    checkAnswers(socket);
                })
    
                socket.on("playerwrong",function(msg){
    
                    users[socket.id].currQuestion.answered = true:
                    users[socket.id].currQuestion.answer = false: 
                    users[socket.id].responses.push(msg.answer);
    
                    checkAnswers(socket);
                })
    
    
        })
    
    
    })
    
    io.sockets.on('disconnect', function(socket){
        delete users[socket.id];
    })
    
    
    
    
    function checkAnswers(socket){
    
          var connectedC = Object.keys(users).length;
    
           for (var clientK in users) {
    
               // check if current q has been answered
    
               if(users[clientK].currQuestion.answered) {
                validCurrQuestion.push({socket:socket,answer:users[clientK].currQuestion.answer});
    
                  if (validCurrQuestion.length === connectedC) {
                      // curr question answered by both clients
                      // send result to both
                      sendCurrQresults();
    
                  }
    
               }
    
               // if the 8 questions have been answered
               // push into array
               if (users[clientK].responses.length === 8) {
                validQuestions.push(socket.id);
               } 
    
               // if all users have answered all question send game results
               if (validQuestions.length === connectedC) {
                // finish the game
                getWinner()
               }
    
           }
    
    }
    
    function sendCurrQresults(){
    
      validCurrQuestion.forEach(function(question, index){
        question.socket.emit("updateplayer", {answer: question.answer});
    
        // reset curr question to go to next question
        validCurrQuestion.splice(index, 1);
        users[socket.id].currQuestion = { answered: false, answer: null};
    
      })
    
    }
    
    function getWinner(){
    
        // Check who has more true response and send by counting user.responses true vs false
    
    }
    

    【讨论】:

    • 我已根据您的建议更新了我的逻辑。但它似乎没有开火。我在我的主服务器端文件夹中包含了一个 pastebin 及其实现。
    • 我在手机上打代码不容易。我已经更新了我的答案,以显示如何比较有效数字响应是否等于连接用户数
    • 基本上存储已连接的用户及其响应,并检查每个用户的响应数是否等于您期望的响应数。如果是这样,更新一个数组并将这个数组的长度与连接用户的长度进行比较。当我回到家时,我会放一个工作代码。我现在在餐厅;)
    • 将不胜感激。会试一试。对所有这些东西都非常陌生。因为我仍然希望能够在每次用户做某事时运行它。所以对我来说都很奇怪。
    • 别担心你会得到它的工作;)坚持是关键。我会在一个小时左右更新答案。抱歉耽搁了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多