In a program I'm working on, I have two devices talking to each other over Bluetooth. When the application is first started, both devices connect fine, but when the connection is severed and re-initialized (i.e. the server thread is killed and then recreated), it fails despite the BluetoothServerSocket
readily accepting connections. On the server side I have
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);
}
}
And on the client side I have
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);
}
}
After restarting the Server and attempting to reconnect, the client times out with the message
java.io.IOException: read failed, socket might closed or timeout, read ret: -1
on the socket.connect();
line. I see the message preparing to connect
in Logcat when monitoring the client, and the message accepting
when monitoring the server, but it never advances beyond that point.