我正在使用 java 7 的 nio2 AsynchronousSocketChannel 来使用 CompletionHandlers 执行读取和写入操作。首先我想知道写操作是否能保证完全写出ByteBuffer。如果是部分写入,则使用 CompletionHandler 可以完全写出 ByteBuffer。也许使用递归?
阅读也是如此。我保证从 AsynchronousSocketchannel 完全读取整个消息,或者也可以部分读取。如果是这样,再次使用 CompletionHandlers 我如何编写一个执行完整读取操作的处理程序。
提前感谢您 弗朗西斯
最佳答案
read
和 write
操作都不能保证写入或读取缓冲区的全部内容。它们只是读取或写入底层套接字中可用于读取操作的任何内容,或者操作系统可以在缓冲区中放入多少内容以进行写入操作。
要可靠地进行完全读/写,只要缓冲区中有一些剩余空间/字节,您就需要重复读
/写
操作:
ByteBuffer buffer = ByteBuffer.allocate(full_size_I_do_expect);
channel.read(buffer, null,
new CompletionHandler() {
@Override
public void completed(Integer result, Object attachment) {
if (result < 0) {
// handle unexpected connection close
}
else if (buffer.remaining() > 0) {
// repeat the call with the same CompletionHandler
channel.read(buffer, null, this);
}
else {
// got all data, process the buffer
}
}
@Override
public void failed(Throwable e, Object attachment) {
// handle the failure
}
});
关于java - NIO2 AsynchronousSocketChannel 完全使用 CompletionHandler 进行读/写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58004883/