Java AIO初探(异步网络IO)
2009-09-22 00:00:00 来源:WEB开发网this.asynchronousChannelGroup = AsynchronousChannelGroup
.withCachedThreadPool(Executors.newCachedThreadPool(),
this.threadPoolSize);
然后初始化一个AsynchronousServerSocketChannel,通过open方法:
this.serverSocketChannel = AsynchronousServerSocketChannel
.open(this.asynchronousChannelGroup);
通过nio 2.0引入的SocketOption类设置一些TCP选项:
this.serverSocketChannel
.setOption(
StandardSocketOption.SO_REUSEADDR,true);
this.serverSocketChannel
.setOption(
StandardSocketOption.SO_RCVBUF,16*1024);
绑定本地地址:
this.serverSocketChannel
.bind(new InetSocketAddress("localhost",8080), 100);
其中的100用于指定等待连接的队列大小(backlog)。完了吗?还没有,最重要的监听工作还没开始,监听端口是为了等待连接上来以便accept产生一个AsynchronousSocketChannel来表示一个新建立的连接,因此需要发起一个accept调用,调用是异步的,操作系统将在连接建立后,将最后的结果——AsynchronousSocketChannel返回给你:
public void pendingAccept() {
if (this.started && this.serverSocketChannel.isOpen()) {
this.acceptFuture = this.serverSocketChannel.accept(null,
new AcceptCompletionHandler());
} else {
throw new IllegalStateException("Controller has been closed");
}
}
更多精彩
赞助商链接