inputStream.read方法阻塞解析以及读取数据不全

目前在做一个串口通信的app,过程中pc模拟单片机给开发板串口发送命令时候出现了问题,inputStream.read方法一直阻塞,完全无法读取到数据,用了网上一个方法,while判断size=-1时候跳出循环,实际上,根本不会跳出去。

read方法是这样的:

*Reads some number of bytes from the input stream and stores them into
* the buffer array <code>b</code>. The number of bytes actually read is
* returned as an integer.  This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
*
* <p> If the length of <code>b</code> is zero, then no bytes are read and
* <code>0</code> is returned; otherwise, there is an attempt to read at
* least one byte. If no byte is available because the stream is at the
* end of the file, the value <code>-1</code> is returned; otherwise, at
* least one byte is read and stored into <code>b</code>.
*
* <p> The first byte read is stored into element <code>b[0]</code>, the
* next one into <code>b[1]</code>, and so on. The number of bytes read is,
* at most, equal to the length of <code>b</code>. Let <i>k</i> be the
* number of bytes actually read; these bytes will be stored in elements
* <code>b[0]</code> through <code>b[</code><i>k</i><code>-1]</code>,
* leaving elements <code>b[</code><i>k</i><code>]</code> through
* <code>b[b.length-1]</code> unaffected.
*
* <p> The <code>read(b)</code> method for class <code>InputStream</code>
* has the same effect as: <pre><code> read(b, 0, b.length) </code></pre>

简答翻译一下就是:

从输入流中读取一些字节数并将它们存储到缓冲区数组b 中。实际读取的字节数以整数形式返回。此方法将阻塞,直到输入数据可用,检测到文件结尾或引发异常。

如果b 的长度为零,则不读取任何字节,并返回 0 ;否则,尝试读取至少一个字节。如果没有字节可用,因为流位于文件的末尾,则返回值-1 ;否则,至少读取一个字节并将其存储到 b 中。 读取的第一个字节存储在元素 b [0] 中, next存入 b [1] ,依此类推。读取的字节数最多等于b 的长度。设 k为实际读取的字节数;这些字节将存储在元素b [0] 到 b [ k -1] ,离开元素b [ k ] 到 b [b.length-1] 不受影响。 类 InputStream 的read(b)方法具有与以下相同的效果:read(b,0,b.length)

这个方法能够正常读取文件流,因为文件总是有大小的,所以总能读到末尾返回-1,但是串口(貌似网络)流也是这样,完全无法判断在哪结束,也无法抛出异常,所以,并不会返回任何数值。

我之前还出现过一个问题,我以为是串口app每次读取四个字节,实际上后来发现是我pc串口助手所用的发送的数据格式,数据位就是8。

所以最后,决定只能设置超时时间

扫描二维码关注公众号,回复: 6148504 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_42039823/article/details/88990812