DataInputStream 卡在 readFully 上
我有一个BluetoothSocket,我正在使用GUI 中的单独线程进程从中读取数据。我将 InputStream 包装在 DataInputStream 中,这样我就可以使用 aa readFully(..) 来等待指定数量的数据。我可以运行这段代码大约一个小时,然后程序锁定,当我调试它时,它卡在 readFully() 处。我在 GUI 线程中添加了 BroadcastReceivers,以便在蓝牙断开连接时通知我。 BroadCastReceiver 永远不会收到通知。不知道为什么设备只是停止发送数据(如果是这种情况),或者甚至不确定蓝牙 SPP 是否已断开但套接字仍然打开,因此蓝牙断开消息永远不会发生。任何有关修复甚至为什么或如何调试其卡住原因的想法都将不胜感激。
这是我的 ReadBlueTooth 课程...
public class ReadBlueToothData extends Thread {
private BluetoothSocket btSocket;
private BluetoothAdapter bta;
private DataInputStream dinput;
public ReadBlueToothData(Activity a,String mac) {
...init object...
}
public void run() {
// if socket connected otherwise stop
if (dinput==null) return;
byte[] byteArray = new byte[3];
while (!Thread.interrupted()) {
dinput.readFully(byteArray, 0, 3);
// DO something ....
}
// close out InputStream nicely
if (dinput!=null) {
try {
dinput.close();
} catch (IOException e) { }
}
if (btSocket != null) {
try {
btSocket.close();
} catch (IOException e) {}
}
}
}
I have a BluetoothSocket that I am reading data from, using a separate Thread process from the GUI. I wrap the InputStream in DataInputStream so I can do use a a readFully(..) to wait for a specified amount of data. I can run this code for about an hour and then the program locks up and when I debug its stuck at the readFully(). I included in my GUI thread BroadcastReceivers to notify me when the bluetooth disconnects. The BroadCastReceivers never get notified. Not sure why the device just stops sending data if that is the case or not eve sure if the Bluetooth SPP gets dropped but the socket is still open so the Bluetooth Disconnect message never happens. Any ideas as to the fix or even why or how to debug why its stuck would be appreciated.
Here is my ReadBlueTooth class...
public class ReadBlueToothData extends Thread {
private BluetoothSocket btSocket;
private BluetoothAdapter bta;
private DataInputStream dinput;
public ReadBlueToothData(Activity a,String mac) {
...init object...
}
public void run() {
// if socket connected otherwise stop
if (dinput==null) return;
byte[] byteArray = new byte[3];
while (!Thread.interrupted()) {
dinput.readFully(byteArray, 0, 3);
// DO something ....
}
// close out InputStream nicely
if (dinput!=null) {
try {
dinput.close();
} catch (IOException e) { }
}
if (btSocket != null) {
try {
btSocket.close();
} catch (IOException e) {}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当检测到蓝牙断开连接时,通过优雅地执行此操作,我不会再收到此错误。
然后通过查看传入的数据进行检查,如果缓冲区的大小没有增加,则也调用断开连接。
I don't get this error anymore by doing this gracefully when detecting a Bluetooth disconnect.
and also then do a check by looking at the data coming in and if the buffer doesn't increase in size then also call disconnect.