Search code examples
javaniojava-7

SocketChannel read() behaviour - short reads


The ServerSocketChannel is used this way:

ServerSocketChannel srv = ServerSocketChannel.open();
srv.socket().bind(new java.net.InetSocketAddress(8112));
SocketChannel client = srv.accept();

When a connection is received, data is read this way:

ByteBuffer data = ByteBuffer.allocate(2000);
data.order(ByteOrder.LITTLE_ENDIAN);
client.read(data);
logger.debug("Position: {} bytes read!", data.position());

It prints:

Position: 16 bytes read!

Why isn't the SocketChannel blocking until the buffer is filled?
From the ServerSocketChannel.accept() API (Java 7):

The socket channel returned by this method, if any, will be in blocking mode regardless of the blocking mode of this channel.

Does the write(ByteBuffer buffer) of the SocketChannel block? How do I test that anyway?

Thank you for your time!


Solution

  • Blocking mode means that it blocks until any data is received. It doesn't have to be an entire buffer full.

    If you want to make sure you've received an entire bufferful of data, you should read() in a loop until you've filled up your buffer.