skyin
skyin

Reputation: 578

Unblocked read from InputStream of a BlueToothSocket while checking connection of the socket

I am trying to write a thread which will do following stuffs:

1. read from inputstream;

2. some other routine;

3. if socket is closed, throw an exception.

The BlueTooth Socket and inputStream from the socket has been set up before this. The code is as following:

public void run() {
    byte[] buffer = new byte[1024];
    int bytes;

    while (true) {
        try {
            //if(mInputStream.available() > 0){        //-------- Line 1
            bytes = mInputStream.read(buffer);
            //}                                      //-------- Line 2

            //---------------------//
            // some other routines //
            //---------------------//

        } catch (IOException e) {
            connectionLost();
            break;
        }               
    }
}

The problem is that the above code will hang at mInputStream.read() because of the blocking. However, if I uncomment Line 1 and Line 2, the mInputStream.available() function will not throw exception even if BlueToothSocket is closed. Is there any method either to unblock read function, or to throw an exception when available() is used and BlueTooth Socket is closed? Appreciate it!

Upvotes: 1

Views: 1452

Answers (2)

user1843784
user1843784

Reputation: 55

This is what I use:

private boolean receivedInTimelyManner(InputStream mInStream,
        int bytesToReceive, long timeoutMillis) throws IOException,
        InterruptedException {

    long time = 0;
    while (mInStream.available() < bytesToReceive && time < timeoutMillis) {

        time+=5;
        Thread.sleep(5);
    }
    if (time == timeoutMillis) {
        return false;
    }
    return true;

}

Surround your read block with something like:

if receivedInTimelyManner(instream,bytes,timeout){
    read()
}

Upvotes: 1

skyin
skyin

Reputation: 578

Ok, seems there is not an easy way to do unblocked read() and available() throwing is not working. The most convenient way to work this out is to create another thread to do the other routines. While leave this thread alone particularly for reading inputstream and checking inputstream status(exception thrown).

Upvotes: 0

Related Questions