简体   繁体   English

在Android中通过蓝牙发送字符串(字节)

[英]Sending strings (bytes) over Bluetooth in Android

I'm implementing sending data through Bluetooth in Android between two Android devices. 我正在实现在两个Android设备之间通过Android中的蓝牙发送数据的功能。 For simplicity, I'll mostly likely pass strings and parse them as JSON or other string format. 为简单起见,我很可能会传递字符串并将其解析为JSON或其他字符串格式。

Now I'm wondering, how should I read the data to be sure, that I've received all of them? 现在我想知道,我应该如何读取数据以确保已收到所有数据? Currently I'm taking the following approach: 目前,我正在采用以下方法:

byte[] buffer = new byte[1024];

while (!finished) {

    // My class
    MemoryStream ms = new MemoryStream();

    int bytesRead = 0;
    do {
        bytesRead = input.read(buffer, 0, buffer.length);
        ms.write(buffer, 0, bytesRead);
    } while (bytesRead == buffer.length);

    // Now process data
}

However, this will work only if inputStream.read() will always return as many bytes as were sent on the other device. 但是,仅当inputStream.read()始终返回与其他设备上发送的字节数相同的字节时,此方法才有效。

For example, I'm assuming, that if first device sends 1234 bytes, first call to read will return 1024 and second 210. Or if first device sends 1024 bytes, first call to read will return 1024 bytes and second - -1 (stream end). 例如,我假设,如果第一个设备发送1234个字节,则第一次read调用将返回1024,第二个为210。或者,如果第一个设备发送1024个字节,则第一次read调用将返回1024个字节,而第二个--1(stream结束)。

Am I right? 我对吗? Or should I implement my own mechanism of determining, whether all sent data was received (or should I wait for more to complete current chunk)? 还是应该实施自己的确定是否已接收到所有已发送数据的机制(还是应该等待更多信息来完成当前块)?

The answer is: no . 答案是: It is possible, that transmission will end (in terms of input.read ) and not the whole sent buffer is transferred. 传输可能会终止(就input.read ),而不是整个发送的缓冲区input.read传输。

One has to guard transmission, preferably by preceeding the data with their size in bytes and then read data until all of them are transferred. 必须保护传输,最好是在数据前放置其大小(以字节为单位),然后读取数据,直到所有数据都被传输为止。

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

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