You may be interested in socket channels if you are not worried about blocking. Channels can be found in the java.nio package. In particular, you might be interested in the ReadableByteChannel
interface and the classes that implement it.
You would use channels like this.
SocketChannel channel = SocketChannel.open(new InetSocketAddress("127.0.0.1",8000)); ByteBuffer buffer = ByteBuffer.allocate(1024); while(channel.read(buffer) != -1) { // if -1 is returned then stream has been closed and loop should exit if (buffer.remaining() == 0) { // buffer is full, you might want to consume some of the data in buffer // or allocate a larger buffer before continuing } // we have now just read as much was available on the socket channel. Any // immediate attempts to read from the channel again will result in the // read method returning immediately. // Hence try to do something useful with the data before reading again } // channel is now closed
source share