SocketChannel read() behaviour - short reads

霸气de小男生 提交于 2019-12-02 14:33:06

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/8202331/socketchannel-read-behaviour-short-reads

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!