Skip to content

调整64字节为1024字节防止数据丢失bug #59

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

ZHUIMEN
Copy link
Contributor

@ZHUIMEN ZHUIMEN commented Dec 11, 2024

让我详细解释为什么固定64字节的缓冲区会导致数据丢失:
串口数据流的特点:

  • 串口通信是持续的数据流
  • 数据可能以不同速率到达
  • 单次传输的数据量可能大于64字节

原代码中的问题:
byte[] buffer = new byte[64]; size = in.read(buffer);

  • in.read(buffer) 最多只能读取64字节
  • 如果串口缓冲区中有100字节数据:
  • 第一次读取:读64字节,剩余36字节
  • 下一次循环:可能在处理这64字节期间,新数据又到达
  • 原有的36字节可能被新数据覆盖或丢失

主要改进包括:
把缓冲区大小从64字节增加到1024字节,并定义为常量

1.添加了10毫秒的休眠时间,减少CPU占用
2.增加了更详细的错误日志
3.使用单独的数据缓冲区,避免数据覆盖

这些修改能够:

  • 防止数据丢失
  • 提高读取大量数据时的可靠性
  • 降低CPU使用率
  • 提供更好的错误处理和日志记录
  • 如果您的串口数据量特别大,可以根据需要调整 BUFFER_SIZE 的值。
    fixbug:
    onReceived buff 最长64位吗? #52

@bastengao
Copy link
Owner

bastengao commented Jan 3, 2025

对缓存区的数据没有读到,会被下次发送数据覆盖这点我存疑。原因你也说了,他是数据流,会按顺序被读到,这次读不到下次也会读到的。

sender.sendEvent(DataReceivedEvent, event);
}

Thread.sleep(10);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里不需要强制休眠,Inputstream.read 方法是阻塞,如果没有读到数据会阻塞住,并不是一直空跑 while 循环

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants