Java AIO初探(异步网络IO)
2009-09-22 00:00:00 来源:WEB开发网AsynchronousSocketChannel的read调用与AsynchronousServerSocketChannel的accept调用类似,同样是非阻塞的,返回结果也是一个Future,但是写的结果是整数,表示写入了多少字节,因此read调用返回的是 Future<Integer>,方法的第一个参数是读的缓冲区,操作系统将IO读到数据拷贝到这个缓冲区,第二个参数是传递给 CompletionHandler的attchment,第三个参数就是注册的用于回调的CompletionHandler。这里保存了read的结果Future,这是为了在关闭连接的时候能够主动取消调用,accept也是如此。现在可以看看read的CompletionHandler的实现:
public final class ReadCompletionHandler implements
CompletionHandler<Integer, AbstractAioSession> {
private static final Logger log = LoggerFactory
.getLogger(ReadCompletionHandler.class);
protected final AioTCPController controller;
public ReadCompletionHandler(AioTCPController controller) {
this.controller = controller;
}
@Override
public void cancelled(AbstractAioSession session) {
log.warn("Session(" + session.getRemoteSocketAddress()
+ ") read operation was canceled");
}
@Override
public void completed(Integer result, AbstractAioSession session) {
if (log.isDebugEnabled())
log.debug("Session(" + session.getRemoteSocketAddress()
+ ") read +" + result + " bytes");
if (result < 0) {
session.close();
return;
}
try {
if (result > 0) {
session.updateTimeStamp();
session.getReadBuffer().flip();
session.decode();
session.getReadBuffer().compact();
}
} finally {
try {
session.pendingRead();
} catch (IOException e) {
session.onException(e);
session.close();
}
}
controller.checkSessionTimeout();
}
@Override
public void failed(Throwable exc, AbstractAioSession session) {
log.error("Session read error", exc);
session.onException(exc);
session.close();
}
}
更多精彩
赞助商链接