为了账号安全,请及时绑定邮箱和手机立即绑定

Socket IO事件多次触发NodeJS

Socket IO事件多次触发NodeJS

慕婉清6462132 2022-06-15 10:47:23
我正在使用 socket.IO 在 NodeJS 和 Android 中构建一个测验应用程序,当我quizzoStatus从服务器发出一个事件时,我遇到了一个问题,该事件第一次触发一次,第二次触发两次,依此类推。在这里我附上我的代码片段///server side: NodeJSsocket.on('sendQuizzoAnsPoints', async (data)=>{          try {              const obj = JSON.parse(data);              const game = await QuizzoPlayModel.findOne({_id:obj.gameId});              const player = await UserModel.findOne({_id: game.playerId});              const opponent = await UserModel.findOne({_id: game.opponentId});              if(obj.userId == game.opponentId){                  let update = {                      opponentPoints: game.opponentPoints + obj.points || 0,                      opponentWA: game.opponentWA + obj.wrongAns || 0,                  };                  await QuizzoPlayModel.findByIdAndUpdate(obj.gameId, update).lean().exec();                  userNamespace.to(player.socketId).emit('quizzoStatus', {                      fullName: opponent.fullName,                      points: game.playerPoints + obj.points,                      wrongAns: obj.wrongAns,                      gameId: obj.gameId                  });              }              if(obj.userId == game.playerId) {                  let update = {                      playerPoints: game.playerPoints + obj.points || 0,                      playerWA: game.playerWA + obj.wrongAns || 0,                  };                  await QuizzoPlayModel.findByIdAndUpdate(obj.gameId, update).lean().exec();                  userNamespace.to(opponent.socketId).emit('quizzoStatus', {                      fullName: player.fullName,                      points: game.playerPoints+ obj.points,                      wrongAns: obj.wrongAns,                      gameId: obj.gameId                  });              }          } catch (e) {              console.log(e);          }        });在这里,我监听一个名为的事件sendQuizzoAnsPoints,然后在另一个名为 的事件中向玩家或对手发出一个事件quizzoStatus。
查看完整描述

1 回答

?
白板的微信

TA贡献1883条经验 获得超3个赞

问题出在Android. 您每次都在分配新的侦听器,而不会删除前一个侦听器。您需要创建该Emmiter侦听器的变量,并在工作完成后将其删除onDestroy或其他地方:


    //variable of Emmiter.Listener

    Emmiter.Listener quizzoStatus = new Emitter.Listener(){

        @Override public void call(Object... args){

            runOnUiThread(new Runnable(){

                @Override public void run(){

                    Log.e("opponet point", opponentPoints + " " + quizzoStatusResponseDto.getPoints());

                }

            });

        }

    };


    //assigning the listener

    socket.on("quizzoStatus", quizzoStatus);

    . . . .

    @Override protected void onDestroy(){

        super.onDestroy();

        //removing the listener...

        socket.off("quizzoStatus", quizzoStatus);

    }

希望这会奏效


查看完整回答
反对 回复 2022-06-15
  • 1 回答
  • 0 关注
  • 178 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号