node.js - 服务端通过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 秒内
打印出服务器触发的对象和对象。当两个命令都运行两次时,不稳定就会出现,或者本身的对象无论如何都会延迟显示。
我不确定问题是不是从服务器发送的,还是没有在客户端的控制台中打印...首先加载,然后每次更改时触发。无法解释的行为question
End event done.
question
useEffect()
questionID
当倒计时组件触发超时时,你可能会提到打印和 4 秒会话延迟这 2 个重要命令被莫名其妙地触发了,这对我来说是无法解释的,ReactJS 的两个独立组件怎么可能“不适合”。
在服务器端,刷新时我会收到“已连接”和“已断开连接”的信息。如果需要更新或对更好的标题有建议,请发表评论。
解决方案
推荐阅读
- docker - 将使用 Docker 容器运行的网站从 HTTP 转换为 HTTPS
- android - Android:Okhttp3:SocketTimeoutException:无法连接到 dns/xx.xx.xx.xx(端口 443)
- php - 由于错误“cURL 错误 60:SSL 证书问题:无法获取本地颁发者证书”而无法获取文件
- angular - 为什么 Angular 在其源代码中使用静态类而不是导出函数?
- c++ - 如何静态制作 CMake 或 OpenCV 链接 [交叉编译 Linux -> Windows]
- plot - 重读命令使 gnuplot 中的动画失真
- php - PHP变量不显示在回声中
- php - foreach 循环中的文件仅包含一次
- vcloud-director-rest-api - vCloudDirector API 无法更改 vApp 的实例化参数
- typescript - 有什么办法可以避免在其他模块中声明的注入令牌的预先声明?