问题描述
ServerSocketChannel
的使用方式如下:
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());
它打印:
为什么直到填充缓冲区后SocketChannel才阻塞?
通过ServerSocketChannel.accept()
API(Java 7):
Why isn't the SocketChannel blocking until the buffer is filled?
From the ServerSocketChannel.accept()
API (Java 7):
SocketChannel块的write(ByteBuffer buffer)
是吗?我该如何测试呢?
Does the write(ByteBuffer buffer)
of the SocketChannel block? How do I test that anyway?
谢谢您的时间!
推荐答案
阻塞模式表示阻塞直到收到任何数据为止.不必整个缓冲区都已满.
Blocking mode means that it blocks until any data is received. It doesn't have to be an entire buffer full.
如果要确保已接收到完整的缓冲数据,则应循环read()
直到填满缓冲区.
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.
这篇关于SocketChannel read()行为-短读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!