我有一个线程不断从输入流读取数据。输入流数据来自蓝牙套接字。以前,我没有在 InputStream read 语句周围使用 if(mmInStream.available() > 0),当蓝牙套接字消失(有人关闭设备)时,mmInStream.read 将抛出 IOException,然后我可以处理我的断开逻辑。确定何时发生断开连接的最佳方法是什么?
0xEE 的第一个字节告诉我它是数据包的领导者,第二个字节告诉我要读取的长度。
public void run() {
byte[] tempBuffer = new byte[1024];
byte[] buffer = null;
int byteRead=0;
long timeout=0;
long wait=100;
while (true) {
try {
timeout = System.currentTimeMillis() + wait;
if(mmInStream.available() > 0) {
while((mmInStream.available() > 0) && (tempBuffer[0] != (byte) 0xEE) && (System.currentTimeMillis() < timeout)){
byteRead = mmInStream.read(tempBuffer, 0, 1);
}
if(tempBuffer[0] == (byte) 0xEE){
timeout = System.currentTimeMillis() + wait;
while(byteRead<2 && (System.currentTimeMillis() < timeout)){
byteRead += mmInStream.read(tempBuffer, 1, 1);
}
}
timeout = System.currentTimeMillis() + wait;
while((byteRead<tempBuffer[1]) && (System.currentTimeMillis() < timeout)){
byteRead += mmInStream.read(tempBuffer, byteRead, tempBuffer[1]-byteRead);
}
}
if(byteRead > 0){
//do something with the bytes read in
}
}
catch (IOException e) {
bluetoothConnectionLost();
break;
}
}
}
最佳答案
你不需要所有这些关于 available() 的胡言乱语。只需使用 setSoTimeout 设置读取超时,读取,检测读取返回 -1,使用 read 返回的计数 if > 0 而不是假设缓冲区已填满,捕获 SocketTimeoutException 来检测读取超时,并捕获 IOException 来检测其他损坏。
关于java - 了解如何在读取套接字数据(InputStream)时检测断开连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11909336/