SocketChannel read() 行为 - 短读取
ServerSocketChannel
的使用方式如下:
ServerSocketChannel srv = ServerSocketChannel.open();
srv.socket().bind(new java.net.InetSocketAddress(8112));
SocketChannel client = srv.accept();
当接收到连接时,数据以这种方式读取:
ByteBuffer data = ByteBuffer.allocate(2000);
data.order(ByteOrder.LITTLE_ENDIAN);
client.read(data);
logger.debug("Position: {} bytes read!", data.position());
它打印:
位置:已读取 16 个字节!
为什么 SocketChannel 在缓冲区填满之前不会阻塞?
从 ServerSocketChannel.accept()
API (Java 7):
此方法返回的套接字通道(如果有)将位于 阻塞模式与该通道的阻塞模式无关。
SocketChannel 的 write(ByteBuffer buffer) 是否会阻塞?我该如何测试呢?
谢谢您的宝贵时间!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
阻塞模式意味着它会阻塞直到接收到任何数据。它不必是整个缓冲区已满。
如果您想确保已收到整个缓冲区的数据,则应循环执行
read()
直至填满缓冲区。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.