在我正在開發的程序中,我有兩個設備通過藍牙相互通話。當應用程序第一次啓動時,兩個設備連接正常,但是當連接被切斷並重新初始化(即服務器線程被終止然後重新創建)時,儘管BluetoothServerSocket
已經接受連接,但它仍然失敗。在服務器端,我有藍牙ServerSocket不接受
void handleConnection() throws Exception {
bss = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord(Constants.BITMAP_NAME,
UUID.fromString(Constants.BITMAP_UUID));
running.set(true);
Logger.logE("accepting");
BluetoothSocket socket = bss.accept();
Logger.logE("accepted");
context.runOnUiThread(new Runnable() {
@Override
public void run() {
if (connectionCallback != null)
connectionCallback.onConnectionMade();
}
});
//handle connection in a loop...
try {
is.close();
is = null;
} catch (IOException ignored) {
Logger.exception(ignored);
}
try {
socket.close();
socket = null;
} catch (IOException ignored) {
Logger.exception(ignored);
}
}
而且在客戶端上我有
void handleConnection() throws Exception {
BluetoothSocket socket = connect.
createRfcommSocketToServiceRecord(UUID.fromString(Constants.BITMAP_UUID));
Logger.logE("preparing to connect");
socket.connect();
Logger.logE("Connected");
if (connectionCallback != null) {
context.runOnUiThread(new Runnable() {
@Override
public void run() {
connectionCallback.onConnectionMade();
}
});
Logger.logE("callback fired");
}
//Handle the connection...
Logger.logE("closing client");
try {
os.close();
os = null;
} catch (Exception ex) {
Logger.exception(ex);
}
try {
socket.close();
socket = null;
} catch (Exception ex) {
Logger.exception(ex);
}
}
重新啓動服務器,並嘗試重新連接,客戶端超時與消息
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
後在socket.connect();
行。在監視客戶端時,我在Logcat中看到消息preparing to connect
,而在監視服務器時看到消息accepting
,但它從未超出這一點。
您能否詳細說明「何時連接被切斷並重新初始化」以及在哪個語句拋出錯誤(java.io.IOException:讀取失敗,套接字可能關閉或超時,讀取ret:-1)? – solosodium
@solosodium爲你更新了它。 – sjyn