【发布时间】:2015-01-13 17:51:31
【问题描述】:
我目前正在尝试使用蓝牙在两个 android 设备之间发送一些数据。我已经阅读了很多关于蓝牙传输、套接字和流的问题。到目前为止没有任何运气。 连接部分正在工作。我得到设备地址,然后使用以下命令打开连接:
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(myOtherDeviceAdress);
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(UUID.fromString(myUUID));
socket.connect();
然后尝试使用OutputStream发送一些数据
OutputStream mmout=tmp.getOutputStream();
byte[] toSend="Hello World!".getBytes();
mmout.write(toSend);
mmout.flush();
在接收端:
mBluetoothServerSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("ccv_prototype", UUID.fromString(myUUID));
mBluetoothSocket = mBluetoothServerSocket.accept(3 * 1000);
InputStream is = mBluetoothSocket.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
然后,当前尝试读取缓冲区的不同版本:
int c;
StringBuilder response = new StringBuilder();
try {
while ((c = r.read()) != -1) {
//Since c is an integer, cast it to a char. If it isn't -1, it will be in the correct range of char.
response.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
String result = response.toString();
Log.d("MyTag", "Received String: " + result);
我的问题是,如果我不关闭OutputStream,接收端永远不会收到EOF,但如果我添加mmout.close();,它甚至没有时间阅读我想要发送的消息就关闭了.到目前为止,我唯一的想法是将特定令牌作为 EOF 发送,但这听起来不对。
我错过了什么? 任何帮助表示赞赏。
【问题讨论】: