Set timeout manually for DataInputStream

I establish a standard TCP connection between two stations (A, B) A sends a message, B receives and sends a response back, and then I close the connections.

  • Station B is a black box, I cannot change access or do anything there.

Sometimes a situation arises when B does not send a response back, and then I need to try the whole process again.

I want to set a timeout for the recovery time of station A (who are waiting for B to respond). So basically, when the timeout expired, I will send a retry.

I did not find a way to set a timeout for a DataInputStream. (only for the entire socket connection - which I don't 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.

+3
source share
2

SocketChannel DataInputStream.

:

private static final long TIMEOUT = 500;

/**
 * Method receives the Server Response
 */
public <C extends SelectableChannel & ReadableByteChannel>byte[]
receive(C chan) throws IOException
{
    logger.debug(TAG + " Client Recieving...");
    try
    {
        Selector sel = Selector.open();
        SelectionKey key = chan.register(sel, SelectionKey.OP_READ);
        ByteBuffer inputData = ByteBuffer.allocate(1024);
        long timeout = TIMEOUT;
        while (inputData.hasRemaining()) {
            if (timeout < 0L) {
                throw new IOException(String.format("Timed out, %d of %d bytes read", inputData.position(), inputData.limit()));
            }
            long startTime = System.nanoTime();
            sel.select(timeout);
            long endTime = System.nanoTime();
            timeout -= TimeUnit.NANOSECONDS.toMillis(endTime - startTime);
            if (sel.selectedKeys().contains(key)) {
                chan.read(inputData);
            }
            sel.selectedKeys().clear();
        }
        return inputData.array();
    } catch (Exception e)
    {
        throw new Exception(TAG + " Couldnt receive data from modem: " + e.getMessage());
    }
}
+1

socket.setSoTimeout(timeout)

-, . : InputStream ?

. , , available(). , n . , , . , .

+1

Source: https://habr.com/ru/post/1784918/


All Articles