java - Unblocked read from InputStream of a BlueToothSocket while checking connection of the socket -
i trying write thread following stuffs:
1. read inputstream;
2. other routine;
3. if socket closed, throw exception.
the bluetooth socket , inputstream socket has been set before this. code 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 //---------------------// // other routines // //---------------------// } catch (ioexception e) { connectionlost(); break; } } }
the problem above code hang @ minputstream.read() because of blocking. however, if uncomment line 1 , line 2, minputstream.available() function not throw exception if bluetoothsocket closed. there method either unblock read function, or throw exception when available() used , bluetooth socket closed? appreciate it!
this 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 read block like:
if receivedintimelymanner(instream,bytes,timeout){ read() }