Java AIO初探(异步网络IO)
2009-09-22 00:00:00 来源:WEB开发网注意,重复的accept调用将会抛出PendingAcceptException,后文提到的read和write也是如此。accept方法的第一个参数是你想传给CompletionHandler的attchment,第二个参数就是注册的用于回调的CompletionHandler,最后返回结果Future<AsynchronousSocketChannel>。你可以对future做处理,这里采用更推荐的方式就是注册一个CompletionHandler。那么accept的CompletionHandler中做些什么工作呢?显然一个赤裸裸的 AsynchronousSocketChannel是不够的,我们需要将它封装成session,一个session表示一个连接(mina里就叫 IoSession了),里面带了一个缓冲的消息队列以及一些其他资源等。在连接建立后,除非你的服务器只准备接受一个连接,不然你需要在后面继续调用pendingAccept来发起另一个accept请求:
private final class AcceptCompletionHandler implements
CompletionHandler<AsynchronousSocketChannel, Object> {
@Override
public void cancelled(Object attachment) {
logger.warn("Accept operation was canceled");
}
@Override
public void completed(AsynchronousSocketChannel socketChannel,
Object attachment) {
try {
logger.debug("Accept connection from "
+ socketChannel.getRemoteAddress());
configureChannel(socketChannel);
AioSessionConfig sessionConfig = buildSessionConfig(socketChannel);
Session session = new AioTCPSession(sessionConfig,
AioTCPController.this.configuration
.getSessionReadBufferSize(),
AioTCPController.this.sessionTimeout);
session.start();
registerSession(session);
} catch (Exception e) {
e.printStackTrace();
logger.error("Accept error", e);
notifyException(e);
} finally {
pendingAccept();
}
}
@Override
public void failed(Throwable exc, Object attachment) {
logger.error("Accept error", exc);
try {
notifyException(exc);
} finally {
pendingAccept();
}
}
}
更多精彩
赞助商链接