Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

---Update---

I had an idea, make 2 thread code herereads(t1 & t2) where each thread interrupt other, one of them(t1) do a sleep(5000) then interrupt the other thread(t2), from the other side the other thread(t2) if in read the inputstream detects some character as 0x0D interrupt the other thread(t1), but here is my question, does anybody can help me? because i didn't use interrupt() method of threads, I hope someone can help me, thank you...

---Update---



        public void run(){
        while(true){
            try {
            char r;
            String respuesta = "";
            while (true) {
                    r = (char) mmInStream.read();
                respuesta += r;
                if (r == 0x3e) {
                break;
                    }
                }
            respuesta = respuesta.replaceAll(" ", "");
            Log.d("respuesta", respuesta);
            rHandler.obtainMessage(MESSAGE_READ, -1, -1, respuesta).sendToTarget();
            } catch (IOException readException) {
            Log.e("ServicioGeneral", "Error de lectura", readException);
            this.interrupt();
            connectionLost();
            // posibly break();
            }
        }
    }

This is my implementation when something comes in a different Thread, the problem is that the timeout will be reached if i dont get the 0x3e character from de mmInStream.

I supposed that in the second example i must use a notifyAll(), but, when do I have to start the readThread()?

Thank you, @weeman

like image 961
Poperto Arcadio Buendía Avatar asked May 09 '12 19:05

Poperto Arcadio Buendía


People also ask

How do I set the timeout of a socket input stream?

For both TCP client and server, we can specify the amount of time the socketInputStream.read() method blocks with the setSoTimeout(int timeout) method: Socket socket = new Socket(host, port); socket.setSoTimeout(30000); However, if the timeout elapses before the method returns, the program will throw a SocketTimeoutException. 5. Conclusion

What is sockettimeoutexception in thread main Java?

Exception in thread "main" java.net.SocketTimeoutException: Connect timed out For the server-side, we'll use the setSoTimeout (int timeout) method to set a timeout value. The timeout value defines how long the ServerSocket.accept () method will block: ServerSocket serverSocket = new new ServerSocket (port); serverSocket.setSoTimeout (40000);

What are socket timeout exceptions in Java?

Introduction In this tutorial, we'll focus on the timeout exceptions of Java socket programming. Our goal is to understand why these exceptions occur and how to handle them. 2. Java Sockets and Timeouts A socket is one end-point of a logical link between two computer applications.

What is the timeout unit of sockettimeoutexception?

The timeout unit is in milliseconds and should be greater than 0. However, if the timeout expires before the method call returns, it will throw a SocketTimeoutException:


2 Answers

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) else 0
    }
    var byteCount = 0
    var retries = 3
    while (byteCount == 0 && retries > 0) {
        withTimeout(timeout) {
            byteCount = readAsync.await()
        }
        delay(timeout)
        retries--
    }
    byteCount
}
like image 171
NSaran Avatar answered Sep 28 '22 22:09

NSaran


You could do something like this:

InputStream in = someBluetoothSocket.getInputStream();
int timeout = 0;
int maxTimeout = 8; // leads to a timeout of 2 seconds
int available = 0;

while((available = in.available()) == 0 && timeout < maxTimeout) {
    timeout++;
    // throws interrupted exception
    Thread.sleep(250);
}

byte[] read = new byte[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:

Thread readThread = new ReadThread(); // being a thread you use to read from an InputStream
try {
   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.

Socket s = new Socket("localhost", 8080);
    final InputStream in = s.getInputStream();

    Thread readThread = new Thread(new Runnable() {
        public void run() {
            int read = 0;
            try {
                while((read = in.read()) >= 0) {
                    System.out.println(new String(new byte[]{ (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();
        }

    }
like image 43
jobnz Avatar answered Sep 28 '22 23:09

jobnz