使用CompletionHandler完全读取/写入NIO2 AsynchronousSocketChannel [英] NIO2 AsynchronousSocketChannel read/write fully using CompletionHandler

查看:111
本文介绍了使用CompletionHandler完全读取/写入NIO2 AsynchronousSocketChannel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java 7的nio2 AsynchronousSocketChannel使用CompletionHandlers执行读取和写入操作.首先,我想知道是否可以保证写操作完全写出ByteBuffer.如果是部分写入,则使用CompletionHandler可以完全写出ByteBuffer.也许使用递归?

I'm using java 7's nio2 AsynchronousSocketChannel to perform read and write operations using CompletionHandlers. Firstly I would like to know if a write operation is guaranteed to write out the ByteBuffer fully or not. If it's a partial write, using CompletionHandler's is there a way to fully write out the ByteBuffer. Maybe using recursion ?

阅读同样.我保证可以从AsynchronousSocketchannel完全读取整个消息,或者也可以部分读取.如果是这样,请再次使用CompletionHandlers如何编写一个可以进行完全读取操作的处理程序.

Same goes for reading. I'm I guaranteed to read the whole message completely from the AsynchronousSocketchannel or can it be a partial read also. If so, again using CompletionHandlers how could I write a handler that would do a full read operation.

预先感谢您 弗朗西斯

推荐答案

readwrite操作均不能保证写入或读取缓冲区的全部内容.他们只是读取或写入底层套接字中可用于读取操作的内容,或者操作系统可在写入操作的缓冲区中放入多少内容.

None of read and write operations are guaranteed to write or read full content of the buffer. They just read or write whatever is available in the underlying socket for the read operation or how much the operating system can put in a buffer for write operation.

要可靠地进行完全读/写操作,只要缓冲区中还有一些剩余空间/字节,就需要重复read/write操作:

To do full read/write reliably you need to repeat the read/write operation as long as there is some remaining space/bytes in the buffer:

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
        }
});

这篇关于使用CompletionHandler完全读取/写入NIO2 AsynchronousSocketChannel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆