1

I want to asynchronously read all bytes from the InputStream of an active tcp connection. There could be nothing in the inputbuffer, in this case I want an empty byte array[] and NOT a read/timeout.

I tried this:

byte[] bytes = IOUtils.toByteArray(tcpInputStream);

But if there is nothing in the InputStream the read hangs until the tcp timeout and then an exception is thrown.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Tobia
  • 9,165
  • 28
  • 114
  • 219
  • IOUtils is not in the standard library ... so what is it and does it offer an asynchronous version? – dsh Jul 23 '15 at 16:21
  • 3
    If you only want to read the data that is *immediately* available, that's what the `available()` call is for. It's rarely useful though... – Jon Skeet Jul 23 '15 at 16:22
  • @dsh: I assume it's apache commons-io. I don't have an answer to this, however, I have found two stackoverflow questions which may help you: http://stackoverflow.com/questions/19833068/async-commons-io-operations and http://stackoverflow.com/questions/5049319/how-to-create-a-java-non-blocking-inputstream-from-a-httpsurlconnection – beosign Jul 23 '15 at 16:37

1 Answers1

0

You can use non blocking SocketChannels:

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

...

SocketChannel socketChannel = SocketChannel.open();
socketChannel.connect(new InetSocketAddress("127.0.0.1", 80));
ByteBuffer buffer = ByteBuffer.allocate(2048);
int bytesRead;
while ((bytesRead = socketChannel.read(buffer)) >= 0) {
    if (bytesRead == 0)
        Thread.sleep(1000); // do usefull stuff
    else {
        // use the bytes and prepare the buffer for next read
        buffer.clear();
    }
}
socketChannel.close();

Also prepare for a IOException when the server closes the connection.

wero
  • 32,544
  • 3
  • 59
  • 84