Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set manually timeout for DataInputStream

I am establishing standart TCP connection between two stations(A,B) A is sending message, B recieving and sending response back, and then I close the connections.

  • Stations B is "blackbox", I cant access change or do anything there.

Sometimes there is situation when B didnt send response back, and then I need to re-try the whole process again.

I want to set timeout on the reciveing time of Station A (which wait for B for an answer). So basically when the waiting time is expired, i will dispatch a retry.

I didnt find a way how to set a timeout for DataInputStream. (only for the whole socket connection - which I dont want)

some code:

 /**
 * Method receives the Server Response
 */
public byte[] receive(DataInputStream is) throws Exception
{
    logger.debug(TAG + " Client Recieving...");

    try
    {

        byte[] inputData = new byte[1024];
                     // here I want to set timeout for the "receiving mode"
        is.read(inputData);
        return inputData;
    } catch (Exception e)
    {
        throw new Exception(TAG + " Couldnt receive data from modem: " + e.getMessage());
    }
}

Thanks, ray.

like image 502
rayman Avatar asked Sep 21 '26 06:09

rayman


1 Answers

First check out socket.setSoTimeout(timeout)

Second, see this discussion: Is it possible to read from a InputStream with a timeout?

read method is blocked. The only way to check whether stream contains data without blocking is using available() method. So you can try to call this method with certain delay and exit if nothing is available after n seconds. You can write your own input stream that wraps any other input stream implementing this logic. The reference above shows how to do this.

like image 141
AlexR Avatar answered Sep 23 '26 22:09

AlexR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!