Socket IO事件多次触发NodeJS

我正在使用 socket.IO 在 NodeJS 和 Android 中构建一个测验应用程序,


当我quizzoStatus从服务器发出一个事件时,我遇到了一个问题,该事件第一次触发一次,第二次触发两次,依此类推。


在这里我附上我的代码片段


///server side: NodeJS

socket.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。


慕婉清6462132
浏览 179回答 1
1回答

白板的微信

问题出在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);    }希望这会奏效
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java