You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Socket.io中host-start-preview事件未触发,但host-start-question-timer事件正常的问题求助

Socket.io中host-start-preview事件未触发,但host-start-question-timer事件正常的问题求助

我现在遇到了一个Socket.io的问题,折腾了好久都找不到原因,特意把代码拆分出来方便大家帮忙排查。

首先是服务器端的socketServer.js代码:

socket.on("start-game", (newQuiz) => {
  quiz = JSON.parse(JSON.stringify(newQuiz));
  console.log(quiz);
  console.log("Move players to game");
  console.log(game.pin);
  socket.to(game.pin).emit("move-to-game-page", game._id);
});

socket.on("question-preview", (cb) => {
  console.log("Received question-preview on the server");
  console.log(game.pin);
  cb();
  console.log("Emitting host-start-preview from the server");
  socket.to(game.pin).emit("host-start-preview");
});

socket.on("start-question-timer", (time, question, cb) => {
  // console.log(question)
  console.log("Send question " + question.questionIndex + " data to players");
  socket.to(game.pin).emit("host-start-question-timer", time, question);
  cb();
});

然后是Host客户端(点击启动按钮的逻辑):

const startGame = () => {
  socket.emit("start-game", quiz);
  socket.emit("question-preview", () => {
    startPreviewCountdown(5, currentQuestionIndex);
  });
  setStage("preview");
};

问题核心:玩家客户端的代码

useEffect(() => {
  console.log("Setting up event listeners on client-side...");
  socket?.on("host-start-preview", () => {
    console.log("HOST STARTED PREVIEW");
    setIsPreviewScreen(true);
    setIsResultScreen(false);
    startPreviewCountdown(5);
  });
  console.log("DOESNT SHOW");
}, [socket]);

useEffect(() => {
  socket.on("host-start-question-timer", (time, question) => {
    console.log("HOST START QUESTION TIMER");
    setQuestionData(question.answerList);
    startQuestionCountdown(time);
    setAnswer((prevstate) => ({
      ...prevstate,
      questionIndex: question.questionIndex,
      answers: [],
      time: 0,
    }));
    setCorrectAnswerCount(question.correctAnswersCount);
  });
}, [dispatch, socket]);

具体现象:

当我以Host身份启动游戏时,服务器端的日志完全符合预期:

Move players to game
5419
Received question-preview on the server
5419
Emitting host-start-preview from the server

Host端一切正常,setStage成功切换到"preview",事件也都正常发出了。

但玩家端的问题来了:host-start-preview事件完全没触发,不过之后的host-start-question-timer事件却能正常触发。

另外,我在玩家端的这个useEffect里能看到socket已经注册了host-start-preview的回调:

useEffect(() => {
  console.log({ socket });
}, [socket]);

真的搞不懂哪里出问题了,提前谢谢大家帮忙!

备注:内容来源于stack exchange,提问作者Strike

火山引擎 最新活动