简体   繁体   English

如何从SerialPort.BaseStream读取没有长度的字节

[英]How to read bytes from SerialPort.BaseStream without Length

I want to use the stream class to read/write data to/from a serial port. 我想使用流类从串行端口读取/写入数据。 I use the BaseStream to get the stream (link below) but the Length property doesn't work. 我使用BaseStream获取流(下面的链接),但是Length属性不起作用。 Does anyone know how can I read the full buffer without knowing how many bytes there are? 有谁知道我如何在不知道有多少字节的情况下读取完整的缓冲区?

http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.basestream.aspx http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.basestream.aspx

You can't. 你不能 That is, you can't guarantee that you've received everything if all you have is the BaseStream . 也就是说,如果您拥有的只是BaseStream ,则不能保证已收到一切。

There are two ways you can know if you've received everything: 您可以通过两种方式知道是否已收到一切:

  1. Send a length word as the first 2 or 4 bytes of the packet. 发送长度字作为数据包的前2或4个字节。 That says how many bytes will follow. 那表示将要跟随多少字节。 Your reader then reads that length word, reads that many bytes, and knows it's done. 然后,您的阅读器将读取该长度的单词,读取那么多字节,并且知道已完成。
  2. Agree on a record separator. 同意记录分隔符。 That works great for text. 这对文本非常有用。 For example you might decide that a null byte or a end-of-line character signals the end of the data. 例如,您可能决定空字节或行尾字符表示数据结束。 This is somewhat more difficult to do with arbitrary binary data, but possible. 使用任意二进制数据很难做到,但有可能。 See comment. 见评论。

Or, depending on your application, you can do some kind of timing. 或者,根据您的应用程序,您可以执行某种计时。 That is, if you haven't received anything new for X number of seconds (or milliseconds?), you assume that you've received everything. 也就是说,如果您在X秒(或毫秒?)内没有收到任何新消息,则认为您已经收到了所有消息。 That has the obvious drawback of not working well if the sender is especially slow. 如果发件人特别慢,那显然有不能正常工作的缺点。

也许您可以尝试SerialPort.BytesToRead属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM