我有一个 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/