我尝试使用两种方法,以便通过蓝牙套接字从InputStream读取数据。
第一个是:
InputStream inputStream = bluetoothSocket.getInputStream();
byte[] buffer = new byte[1024];
inputStream.read(buffer);
String clientString = new String(buffer, "UTF-8");这个方法的问题是,现在在clientString中,原始消息加"0“,直到缓冲区满(如果我使用第一个字节作为指示符,我可以知道消息的长度,但我尽量不这样做)。
第二个是(使用Apache Commons IO中的IOUtils类):
InputStream inputStream = bluetoothSocket.getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, "UTF-8");
String clientString = writer.toString();这个方法的问题是它停留在copy行上,并且永远不会超过这个点。
所以,我的问题是,这些方法之间有什么不同,为什么我会得到不同的结果?
客户端的代码是(使用32feet的C#):
client.Connect(BluetoothEndPoint(device.DeviceAddress, mUUID));
bluetoothStream = client.GetStream();
if (client.Connected == true && bluetoothStream != null)
{
byte[] msg = System.Text.Encoding.UTF8.GetBytes(buffer + "\n");
bluetoothStream.Write(msg, 0, msg.Length);
bluetoothStream.Flush();
}发布于 2014-11-14 01:51:27
我猜IOUtils类来自Apache Commons IO。它从inputStream复制到编写器,直到到达流的末尾(流上的读取方法返回-1)。您的第一个方法只是尝试读取1024字节的最大值,然后继续。
此外,inputStream.read(缓冲区)将返回读取的字节数。所以当你创建字符串的时候,你可以使用:
int read = inputStream.read(buffer);
String clientString = new String(buffer, 0, read, "UTF-8")您还需要检查read方法是否返回-1,表示已到达流的末尾。
https://stackoverflow.com/questions/26914404
复制相似问题