WEB开发网
开发学院软件开发Java Java AIO初探(异步网络IO) 阅读

Java AIO初探(异步网络IO)

 2009-09-22 00:00:00 来源:WEB开发网   
核心提示: this.asynchronousChannelGroup=AsynchronousChannelGroup.withCachedThreadPool(Executors.newCachedThreadPool(),this.threadPoolSize);然后初始化一个Asynchronous

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

上一页  1 2 3 4 5 6 7 8 9  下一页

Tags:Java AIO 初探

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接