---
title: "Nio线程协作"
author: "dylan0514sina.cn"
date: "2013-12-10T10:01:58Z"
tags: []
categories: ["开源软件"]
slug: "nio"
draft: false
lastmod: "2013-12-10T15:22:17Z"
id: 1987553
url: "https://tmmh.iteye.com/blog/1987553"
---

Netty 是一个客户端服务器框架，它基于jdk nio开发。[Netty home](http://netty.io/).
Netty 样例代码如下
客户端
```java

     // Configure the client.
        ClientBootstrap bootstrap = new ClientBootstrap(
                new NioClientSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(
                        new EchoClientHandler(firstMessageSize));
            }
        });

        // Start the connection attempt.
        ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));
        // Wait until the connection is closed or the connection attempt fails.
        future.getChannel().getCloseFuture().awaitUninterruptibly();

        // Shut down thread pools to exit.
        bootstrap.releaseExternalResources();

```

服务器端
```java

  // Configure the server.
        ServerBootstrap bootstrap = new ServerBootstrap(
                new NioServerSocketChannelFactory(
                        Executors.newCachedThreadPool(),
                        Executors.newCachedThreadPool()));

        // Set up the pipeline factory.
        bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            public ChannelPipeline getPipeline() throws Exception {
                return Channels.pipeline(new EchoServerHandler());
            }
        });

        // Bind and start to accept incoming connections.
        bootstrap.bind(new InetSocketAddress(port));
    }

```

处理流程
![](http://dl2.iteye.com/upload/attachment/0091/9990/851373a1-28a5-38a3-990b-d11bae2a4b02.jpg)
NioClientSocketPipelinesink由NioClientSocketChannelFactory创建，责任是分发事件处理
AbstractNioSelector是netty心脏，下面是客户端的AbstractNioSelector实现，包括NioClientBoss,NioWorker,没有画出的部分是服务器端的NioServerBoss，他们的职责及其区别如下流程
![](http://dl2.iteye.com/upload/attachment/0091/9997/8eb5011f-b518-3047-849b-bb2d58ce0b72.jpg)
NioClientBoss,NioServerBoss，NioWorker联系与区别如下。
如上所述NioClientSocketPipelinesink和NioServerSocketPipelinesink分别处理客户端服务器端的由Boostrap触发的事件，有本事身为AbstractNioSelector的Boss线程NioClientBoss，NioServerBoss处理，NioClientBoss处理OP_CONNECT,NioServer处理OP_ACCEPT。
NioClientBoss完成连接后，交由NioWorker线程处理；NioWorker在连接之前已经创建
NioServerBoss接受到多个连接后，交由NioWorker线程处理；NioWorker在接受到连接后创建。递交给NioWorker的方式通过注册到NioWorker任务队列中，当有后续的交互操作时NioWorker会处理任务队列

![](http://dl2.iteye.com/upload/attachment/0092/0001/53cc25a6-3fbb-380f-8d51-05cfdefd9404.jpg)