我的蓝牙插座有问题,我收到IOException
告诉我:Socket Closed
此处发生异常:
} catch (IOException e) {
try {
inputStream.close();
socket.close();
} catch (IOException e1) {
Log.e("CLOSE: ", e.getMessage());
}
Log.e("IO FROM RUN: ", e.getMessage());
}
相关的codenippet:
class AcceptThread extends Thread {
/**
* Tag that will appear in the log.
*/
private final String ACCEPT_TAG = AcceptThread.class.getName();
/**
* The bluetooth server socket.
*/
private final BluetoothServerSocket mServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(
"Bluetooth Service", UUID.fromString(defaultUUID));
} catch (IOException e) {
e.printStackTrace();
}
mServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
Log.i(ACCEPT_TAG, "Listening for a connection...");
socket = mServerSocket.accept();
Log.i(ACCEPT_TAG, "Connected to "
+ socket.getRemoteDevice().getName());
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
ReadInputThread inputThread = new ReadInputThread(socket);
inputThread.start();
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mServerSocket.close();
} catch (IOException e) {
}
}
class ReadInputThread extends Thread {
BluetoothSocket socket;
InputStream inputStream;
public ReadInputThread(BluetoothSocket socket) {
InputStream tempIs = null;
try {
this.socket = socket;
tempIs = socket.getInputStream();
} catch (IOException e) {
Log.e("IO: ", e.getMessage());
}
inputStream = tempIs;
}
public void run() {
Log.i(TAG, "BEGIN ReadInputThread");
final byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
if(inputStream.available() < 0) {
inputStream.close();
socket.close();
}
Log.i("BYTE COUNT: ", Integer.toString(bytes));
Log.i("BYTES: ", new String(buffer));
} catch (IOException e) {
try {
inputStream.close();
socket.close();
} catch (IOException e1) {
Log.e("CLOSE: ", e.getMessage());
}
Log.e("IO FROM RUN: ", e.getMessage());
}
}
}
}
有人能给我一个如何解决这个问题的提示吗?谢谢!
答案 0 :(得分:0)
看起来问题在于此代码:
while (true) {
try {
bytes = inputStream.read(buffer);
if(inputStream.available() < 0) {
inputStream.close();
socket.close();
}
Log.i("BYTE COUNT: ", Integer.toString(bytes));
Log.i("BYTES: ", new String(buffer));
} catch (IOException e) {
try {
inputStream.close();
socket.close();
} catch (IOException e1) {
Log.e("CLOSE: ", e.getMessage());
}
Log.e("IO FROM RUN: ", e.getMessage());
}
}
在你的while循环中,你首先尝试阅读可用的内容,如果没有,则关闭套接字。然后循环重复并尝试再次从套接字读取,但它关闭,给你IOException。 如果要在没有可读数据的情况下退出循环,请确保在socket.close()之后添加一个返回或中断。