InputStream.read 方法调用速度太快
我正在尝试从蓝牙套接字读取 InputStream 数据,并且该方法执行它在开始时应该执行的操作。但由于某种原因,后来它并没有读取所有内容。
这是我现在使用的方法:
public int read(byte[] b, int off, int len)
当我检查字节数组时,它的结束部分是下一部分数据的开始。这意味着 read 方法在完成读取之前就被再次调用。有谁知道如何处理这个问题?
I'm trying to read InputStream data from Bluetooth socket and the method does what it suppose to do at the beginning. But for some reason later on it doesn't read everything.
Here's the method that I'm using right now:
public int read(byte[] b, int off, int len)
When I check the byte array its end part is the beginning of the next part of data. Which means the read method got called again even before it finished reading. Does anyone know how to handle this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须在应用程序协议设计中自己处理这个问题。
假设您将 Android
BluetoothSocket
与 RFCOMM 一起使用,javadoc 会这样说:和
虽然从这些引用中还不清楚,但暗示流的行为将类似于 TCP 流,这意味着不存在可靠可辨别的消息/数据包/记录边界在通过
read
方法传递的字节中。如果发送方决定连续发送两条消息,则接收方有责任在读取缓冲区中获取一条消息的结尾和下一条消息的开头。所以...如果您有一个在套接字上运行的面向消息/数据包的应用程序协议,您必须设计您的应用程序协议,以便接收者可以辨别消息边界,无论一次通过的字节数是多少。换句话说,您需要在协议中使用数据包字节计数、数据包结束标记或类似内容,以允许接收方找出每个数据包的结束位置和下一个数据包的开始位置。
You are going to have to deal with this yourself in your application protocol design.
Assuming that you are using Android
BluetoothSocket
with RFCOMM, the javadoc says this:and
While it is not crystal clear from these quotes, the implication is that the streams will behave like TCP streams, and that means that there are no reliably discernible message / packet / records boundaries in the bytes deliver by the
read
methods. If the sender decides to send two messages back-to-back, then the receiver is liable to get the end of one message and the beginning of the next one in the read buffer.So ... if you have a message / packet oriented application protocol running over the socket, you have to design your application protocol so that the message boundaries are discernible by the receiver irrespective of how few / many bytes come through at a time. In other words, you need to use packet byte counts, end-of-packet markers or some-such in your protocol to allow the receiver to figure out where each packet ends and the next one begins.