Implement A Timeout In Bluetoothsocket Inputstream.read() In Android
Is it possible to implement a timeout in an inputstream.read() function from a BluetoothSocket in Android? I've tried using Thread.sleep() but this only pauses my activity. ---Upda
Solution 1:
You could do something like this:
InputStream in = someBluetoothSocket.getInputStream();
int timeout = 0;
int maxTimeout = 8; // leads to a timeout of 2 secondsint available = 0;
while((available = in.available()) == 0 && timeout < maxTimeout) {
timeout++;
// throws interrupted exception
Thread.sleep(250);
}
byte[] read = newbyte[available];
in.read(read);
This way you are able to initially read from a stream with a specific timeout. If u want to implement a timeout at any time of reading you can try something like this:
ThreadreadThread=newReadThread(); // being a thread you use to read from an InputStreamtry {
synchronized (readThread) {
// edit: start readThread here
readThread.start();
readThread.wait(timeOutInMilliSeconds);
}
catch (InterruptedException e) {}
using this you may need some kind of event handler to notify your application if the thread actually read something from the input stream.
I hope that helps!
----edit:
I implemented an example without using any handlers.
Sockets=newSocket("localhost", 8080);
finalInputStreamin= s.getInputStream();
ThreadreadThread=newThread(newRunnable() {
publicvoidrun() {
intread=0;
try {
while((read = in.read()) >= 0) {
System.out.println(newString(newbyte[]{ (byte) read }));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
synchronized (readThread) {
readThread.start();
try {
readThread.wait(2000);
if(readThread.isAlive()) {
// probably really not good practice!
in.close();
System.out.println("Timeout exceeded!");
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Solution 2:
A Kotlin extension function for socket read with timeout:
fun InputStream.read(
buffer: ByteArray,
offset: Int,
length: Int,
timeout: Long
): Int = runBlocking {
val readAsync = async {
if (available() > 0) read(buffer, offset, length) else0
}
var byteCount = 0var retries = 3while (byteCount == 0 && retries > 0) {
withTimeout(timeout) {
byteCount = readAsync.await()
}
delay(timeout)
retries--
}
byteCount
}
Post a Comment for "Implement A Timeout In Bluetoothsocket Inputstream.read() In Android"