SocketChannel read() 行为 - 短读取

发布于 2024-12-17 08:29:51 字数 765 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

好倦 2024-12-24 08:29:51

阻塞模式意味着它会阻塞直到接收到任何数据。它不必是整个缓冲区已满。

如果您想确保已收到整个缓冲区的数据,则应循环执行 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文