Java 阻塞套接字返回不完整的 ByteBuffer

标签 java sockets nio

我有一个 socketChannel 配置为阻塞,但是当从这个套接字读取 5K 的字节缓冲区时,我有时会得到一个不完整的缓冲区。

    ByteBuffer messageBody = ByteBuffer.allocate(5*1024);
    messageBody.mark();
    messageBody.order(ByteOrder.BIG_ENDIAN);
    int msgByteCount = channel.read(messageBody);

偶尔会出现messageBody没有填满,channel.read()返回的不是-1也不是异常,而是实际读取的字节数(小于5k)。

有没有人遇到过类似的问题?

最佳答案

这就是读取的工作原理。 SocketChannel文档说:

A read operation might not fill the buffer, and in fact it might not read any bytes at all. [...] It is guaranteed, however, that if a channel is in blocking mode and there is at least one byte remaining in the buffer then this method will block until at least one byte is read [emphasis added].

关于Java 阻塞套接字返回不完整的 ByteBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2717023/

相关文章:

linux - Netty 的零拷贝和 OS 级别的零拷贝有区别吗?

java : corrupted zip file created when copy using nio

java - 加载自定义 Android View 时出错 : Resources$NotFoundException: Resource ID #0x7f060007 type #0x12 is not valid

java - 正则表达式 - 为什么这允许空格?

java - 在 spring 中从 ResourceBundleMessageSource 按模式获取属性键

perl - 使用Perl客户端-服务器(套接字)执行远程命令

java - Spring 数据JPA : Generate dynamic query

c++ - 在 C++ 中使用 zeromq 将序列化的 Mat 对象发送到另一台计算机

node.js - Socket.io异步/等待.on()

Java - 在不关闭的情况下中断 I/O