首页 > 解决方案 > 服务端通过socket.io发送的数据显示异常

问题描述

就我而言,Socket.io 的行为非常不稳定。需要使它更易于调试和稳定。
介绍
有一个基于 Node'js 的后端(Strapi CMS),bootstrap.js我有权在其中运行我的自定义代码 - 在我的情况下是套接字服务器:

module.exports = async () => {
  process.nextTick(() =>{
    var io = require('socket.io')(strapi.server);
    io.on('connection', async function(socket) {
      
      console.log(`a user connected`)
      
      // send a message on user connection
      socket.emit('question', {message: await strapi.services.question.findOne({ id: 1 })});
      
      //Send a message after a timeout of 4seconds
      setTimeout(function() {
        socket.emit('endEvent', { description: 'A custom event named EndEvent!'});
      }, 4000);
      // listen for user diconnect
      socket.on('disconnect', () =>{
        console.log('a user disconnected')
      });
    });
    strapi.io = io; // register socket io inside strapi main object to use it globally anywhere
  })
};

该服务器应通过自定义事件从数据库向套接字发送一个问题 - question。前端使用 ReactJS 运行。每当加载页面时,都会创建套接字,它会与服务器建立连接并接收question来自服务器的事件,以及作为对象打印的测验问题的数据。

import React, { useState, useEffect } from "react";
import io from "socket.io-client";

const ENDPOINT = "http://localhost:1337";
const socket = io(ENDPOINT);

function Question() {
  const [questionID,setQuestionID] = useState(0)

  useEffect(() => {
    socket.on('message', (data)=> {setResponse(data)});
    socket.on('endEvent', ()=>{console.log('End event done.')})
    socket.on('question', (msg, cb) => {
      console.log( msg.message)
    });
    // CLEAN UP THE EFFECT
    return () => socket.disconnect();
  }, [questionID]);
return(<p>The question debugable from console</p>);
}
export default Question;

问题
当我刷新页面时,console.log( msg.message)确实会按时打印,但不是每次都打印。有时它只是在触发 React 的其他一些组件时打印。有关详细信息,请参阅屏幕截图。这是意料之中的: 它会在连接后 4 秒内 打印出服务器触发的对象和对象。当两个命令都运行两次时,不稳定就会出现,或者本身的对象无论如何都会延迟显示。 我不确定问题是不是从服务器发送的,还是没有在客户端的控制台中打印...首先加载,然后每次更改时触发。无法解释的行为Strapi socket.io
questionEnd event done.question在此处输入图像描述useEffect()questionID

当倒计时组件触发超时时,你可能会提到打印和 4 秒会话延迟这 2 个重要命令被莫名其妙地触发了,这对我来说是无法解释的,ReactJS 的两个独立组件怎么可能“不适合”。
在服务器端,刷新时我会收到“已连接”和“已断开连接”的信息。如果需要更新或对更好的标题有建议,请发表评论。

标签: node.jsreactjssocket.iostrapi

解决方案


推荐阅读