<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>绿色记忆 &#187; Netty</title>
	<atom:link href="https://blog.gmem.cc/tag/netty/feed" rel="self" type="application/rss+xml" />
	<link>https://blog.gmem.cc</link>
	<description></description>
	<lastBuildDate>Mon, 06 Apr 2026 12:46:48 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.9.14</generator>
	<item>
		<title>Netty学习笔记</title>
		<link>https://blog.gmem.cc/netty-study-note</link>
		<comments>https://blog.gmem.cc/netty-study-note#comments</comments>
		<pubDate>Mon, 02 Dec 2013 01:31:59 +0000</pubDate>
		<dc:creator><![CDATA[Alex]]></dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Network]]></category>
		<category><![CDATA[Netty]]></category>
		<category><![CDATA[NIO]]></category>
		<category><![CDATA[学习笔记]]></category>

		<guid isPermaLink="false">http://blog.gmem.cc/?p=6457</guid>
		<description><![CDATA[<p>Netty简介 Netty是一个基于NIO的客户端-服务器框架，用于支持快速、容易的开发可扩展（Scalable）的网络应用。Netty将网络开发的复杂性隔离出去——将网络处理代码与业务逻辑代码解耦，提供了便于使用的API。 一般来说，网络应用都具有可扩展性问题（Scalability），Netty能解决可扩展性问题的根本是它的异步特性（Asynchronous nature）。 在计算机科学里，引入额外的抽象层是屏蔽复杂性的通用手段。Netty引入了这样的一个抽象层以简化TCP、UDP编程，但是Netty仍然允许通过此抽象层访问低级的API。下面是Netty的特性表格：  开发区域 Netty特性  设计 为不同的传输（Transport）方式提供一致的API：阻塞或非阻塞的套接字 灵活性 简单而强大的线程模型 真正的无连接数据报（Datagram）套接字支持 便于重用的逻辑链API 易用性  大量的例子 除了JDK以外，不需要额外的依赖 性能 比起Java核心API，具有更好的吞吐量、更低的延迟 由于池化、重用，具有更少的资源消耗 最小化不必要的内存拷贝 健壮性 不会因为过快、过慢或者过多的连接导致OutOfMemoryError <a class="read-more" href="https://blog.gmem.cc/netty-study-note">[...]</a></p>
<p>The post <a rel="nofollow" href="https://blog.gmem.cc/netty-study-note">Netty学习笔记</a> appeared first on <a rel="nofollow" href="https://blog.gmem.cc">绿色记忆</a>.</p>
]]></description>
				<content:encoded><![CDATA[<div class="wri_content_clear_both"><div class="blog_h1"><span class="graybg">Netty简介</span></div>
<p>Netty是一个基于NIO的客户端-服务器框架，用于支持快速、容易的开发可扩展（Scalable）的网络应用。Netty将网络开发的复杂性隔离出去——<span style="background-color: #c0c0c0;">将网络处理代码与业务逻辑代码解耦</span>，提供了便于使用的API。</p>
<p>一般来说，网络应用都具有可扩展性问题（Scalability），Netty能解决可扩展性问题的根本是它的异步特性（Asynchronous nature）。</p>
<p>在计算机科学里，引入额外的抽象层是屏蔽复杂性的通用手段。Netty引入了这样的一个抽象层以简化TCP、UDP编程，但是Netty仍然允许通过此抽象层访问低级的API。下面是Netty的特性表格：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;"> 开发区域</td>
<td style="text-align: center;">Netty特性 </td>
</tr>
</thead>
<tbody>
<tr>
<td>设计</td>
<td>
<ol>
<li>为不同的传输（Transport）方式提供一致的API：阻塞或非阻塞的套接字</li>
<li>灵活性</li>
<li>简单而强大的线程模型</li>
<li>真正的无连接数据报（Datagram）套接字支持</li>
<li>便于重用的逻辑链API</li>
</ol>
</td>
</tr>
<tr>
<td>易用性 </td>
<td>
<ol>
<li>大量的例子</li>
<li>除了JDK以外，不需要额外的依赖</li>
</ol>
</td>
</tr>
<tr>
<td>性能</td>
<td>
<ol>
<li>比起Java核心API，具有更好的吞吐量、更低的延迟</li>
<li>由于池化、重用，具有更少的资源消耗</li>
<li>最小化不必要的内存拷贝</li>
</ol>
</td>
</tr>
<tr>
<td>健壮性</td>
<td>
<ol>
<li>不会因为过快、过慢或者过多的连接导致OutOfMemoryError</li>
<li>不会出现高速网络中使用NIO时会出现的不合理读写比率</li>
</ol>
</td>
</tr>
<tr>
<td>安全性</td>
<td>
<ol>
<li>完整的SSL/TLS、StartTLS支持</li>
<li>支持在受限环境使用，包括Applet、OSGI</li>
</ol>
</td>
</tr>
</tbody>
</table>
<div class="blog_h1"><span class="graybg">Netty Echo服务器与客户端</span></div>
<p>服务器端代码：</p>
<pre class="crayon-plain-tag">package cc.gmem.study.network.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cc.gmem.study.network.basic.Helper;


public class EchoServer
{

    private static final Logger LOGGER = LoggerFactory.getLogger( EchoServer.class );

    private final int           port;

    public EchoServer( int port )
    {
        this.port = port;
    }

    public void start() throws Exception
    {
        //事件循环组将网络编程的线程处理部分很好的封装起来
        EventLoopGroup group = new NioEventLoopGroup();
        try
        {
            //要启动服务端，必须实例化下面这个实例
            ServerBootstrap b = new ServerBootstrap();
            b
                    //指定使用的事件循环组，该组用于接受连接、接收/发送数据，等等
                    //可以指定两个事件循环组，分别用于接受连接、读写数据
                    .group( group )
                    //使用非阻塞的套接字传输，必须指定此服务器通道类型，以监听并处理客户端连接
                    .channel( NioServerSocketChannel.class )
                    //绑定的本地监听地址
                    .localAddress( new InetSocketAddress( port ) )
                    //当连接被接受后，会创建NioServerSocketChannel的子通道SocketChannel
                    //childHandler方法用于指定子通道的处理器，通常为ChannelInitializer
                    .childHandler( new ChannelInitializer() {

                        public void initChannel( SocketChannel ch ) throws Exception
                        {
                            //管道（Pipeline）持有某个通道的全部处理器
                            ChannelPipeline pipeline = ch.pipeline();
                            //添加一个处理器
                            pipeline.addLast( new EchoServerHandler() );
                        }
                    } );
            //执行绑定，等待直到成功
            ChannelFuture f = b.bind().sync();
            LOGGER.debug( " started and listen on {}", f.channel().localAddress() );
            //等待服务器通道被关闭
            f.channel().closeFuture().sync();
        }
        finally
        {
            //关闭事件循环，释放相关资源（包括创建的线程）
            group.shutdownGracefully().sync();
        }
    }

    public static void main( String[] args ) throws Exception
    {
        new EchoServer( Helper.DEFAULT_PORT ).start();
    }

    //该注解表示通道处理器类将被不同通道共享
    @Sharable
    public class EchoServerHandler extends ChannelInboundHandlerAdapter
    {

        /**
         * 当从通道读取到数据后，会执行该回调
         * 注意：数据可能碎片化，分若干次读取，这种情况下，该回调会被执行多次
         */
        public void channelRead( ChannelHandlerContext ctx, Object msg )
        {
            ByteBuf buf = (ByteBuf) msg;//注意这里不一定能收到完整的消息
            LOGGER.debug( "Server received: {}", buf.toString( CharsetUtil.UTF_8 ) );
            //将接收到的数据写回去，注意这里还没有将数据刷空以发送到对端（peer）
            //当前方法不使用channelRead0的原因：write可能在channelRead返回前尚未完成（因为异步）
            //如果使用channelRead0，那么msg对应的ByteBuf将被自动释放（release）
            ctx.write( msg );
        }

        /**
         * 当读取数据完毕（没有更多数据可读）后，会执行该回调
         */
        public void channelReadComplete( ChannelHandlerContext ctx )
        {
            //刷空所有数据，并在执行完毕后，关闭通道
            ctx.writeAndFlush( Unpooled.EMPTY_BUFFER ).addListener( ChannelFutureListener.CLOSE );
        }

        /**
         * 当发生任何异常时，执行该回调
         * 至少应当有一个通道处理器覆盖此方法，以实现必要的异常处理
         */
        public void exceptionCaught( ChannelHandlerContext ctx, Throwable cause )
        {
            //关闭通道
            ctx.close();
        }
    }
}</pre>
<p>客户端代码：</p>
<pre class="crayon-plain-tag">package cc.gmem.study.network.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cc.gmem.study.network.basic.Helper;


public class EchoClient
{

    private static final Logger LOGGER = LoggerFactory.getLogger( EchoClient.class );

    private final String        host;

    private final int           port;

    public EchoClient( String host, int port )
    {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception
    {

        EventLoopGroup group = new NioEventLoopGroup();
        try
        {
            //要启动客户端，必须实例化下面这个实例
            Bootstrap b = new Bootstrap();
            b
                    //指定事件循环组
                    .group( group )
                    //指定非阻塞的套接字通道类
                    .channel( NioSocketChannel.class )
                    //指定需要连接的服务器
                    .remoteAddress( new InetSocketAddress( host, port ) )
                    //指定通道的处理器，一旦连接成功就会调用此处理器
                    .handler( new ChannelInitializer() {

                        public void initChannel( SocketChannel ch ) throws Exception
                        {
                            //在通道的尾部添加一个处理器
                            ch.pipeline().addLast( new EchoClientHandler() );
                        }
                    } );
            //连接、等待直到连接成功
            ChannelFuture f = b.connect().sync();
            //等待直到客户端通道被关闭
            f.channel().closeFuture().sync();
        }
        finally
        {
            //关闭事件循环，释放相关资源（包括创建的线程）
            group.shutdownGracefully().sync();
        }
    }

    public static void main( String[] args ) throws Exception
    {
        new EchoClient( Helper.DEFAULT_HOST, Helper.DEFAULT_PORT ).start();
    }

    @Sharable
    public class EchoClientHandler extends SimpleChannelInboundHandler
    {

        /**
         * 一旦与服务器的连接建立，即调用此回调
         */
        public void channelActive( ChannelHandlerContext ctx )
        {
            //发送一个简单的消息给服务器
            //Unpooled是一个工具类，可以分配新的缓冲，或者包装已经存在的字节数组、字节缓冲、字符串
            //copiedBuffer方法可以根据指定的字符串和编码方式，创建一个大端（big-endian）的字节缓冲
            //这里的几个汉字和标点共计21字节
            ByteBuf msg = Unpooled.copiedBuffer( "服务器，你好！", CharsetUtil.UTF_8 );
            //写入数据并刷空，如果不刷空，数据可能存在于本地缓冲，不发送给服务器
            ctx.writeAndFlush( msg );
        }

        /**
         * 从服务器接收到数据后，调用此回调。channelRead0会自动的释放（减少引用计数，如果为0则解构并回收）ByteBuf对象
         * 需要注意的是：接收到的字节可能是碎片化的（channelRead0），虽然上面发送了21字节给服务器
         * 但是可能分多次读取，例如：第一次读取10字节，第二次读取11字节。因此该回调可能被调用多次
         * 唯一能保证的是：在使用TCP或其它面向流的协议的情况下，数据被读取的顺序有保证
         */
        public void channelRead0( ChannelHandlerContext ctx, ByteBuf in )
        {
            int count = in.readableBytes();//可以获取本次可读的字节数
            ByteBuf buf = in.readBytes( count ); //读取为字节缓冲
            Object msg = buf.toString( CharsetUtil.UTF_8 );//转换为字符串形式
            LOGGER.debug( "Client received: {}", msg );
        }

        public void exceptionCaught( ChannelHandlerContext ctx, Throwable cause )
        {
            ctx.close();
        }
    }
}</pre>
<div class="blog_h1"><span class="graybg">Netty核心组件概述</span></div>
<p>一个Netty应用从Bootstrap类（包括ServerBootstrap、Bootstrap）开始，Bootstrap是Netty用于简化Netty配置和启动的一个类。</p>
<p>为了支持各种协议、支持通过不同的方式来处理数据，Netty引入处理器（Handler）的概念，处理器可以处理一种或者多种Netty事件。这里的“事件”是一个泛指的概念，因为某些处理器可以执行对象——字节的转换，与一般的I/O事件并不是一个概念。</p>
<p>一种最常编写的、<span style="background-color: #c0c0c0;">包含了大部分业务逻辑的处理器是ChannelInboundHandler</span>，可以用来接收消息并执行相应的处理，例如可以在此处理器中编写回应消息并write/flush。</p>
<p>当Netty客户端连接到服务器时、服务器监听到客户端连接时，需要知道如何处理消息的收发，即，需要知道使用什么处理器。Netty提供的ChannelInitializer专门用于注册前述的处理器，通过该类，可以将各种处理器注册到通道管道（ChannelPipeline）中。ChannelInitializer本身也是一种处理器，它会在添加了其它处理器后，将自己从管道中移除。</p>
<p>所有Netty应用程序都是基于管道的，与管道相关的概念是事件循环（EventLoop）、事件循环组（EventLoopGroup），这三者与事件、事件处理紧密相关。</p>
<p><span style="background-color: #c0c0c0;">一个事件循环</span>的目的是处理<span style="background-color: #c0c0c0;">多个通道</span>的I/O操作。事件循环组则包含多个事件循环，可以对外提供。一个<span style="background-color: #c0c0c0;">事件循环在其生命周期内绑定到唯一的单个线程</span>。需要注意的是，EventLoopGroup是EventLoop的父接口。</p>
<p><span style="background-color: #c0c0c0;">通道（Channel）</span>代表了一个Socket连接，或者类似的<span style="background-color: #c0c0c0;">支持I/O操作</span>的概念。</p>
<p>Netty中的<span style="background-color: #c0c0c0;">所有I/O操作都是异步</span>的，因此：</p>
<ol>
<li>当连接到服务器时，操作是异步完成的</li>
<li>当读写消息时，操作是异步完成的</li>
</ol>
<p>操作<span style="background-color: #c0c0c0;">不是在当前线程中立即执行，而总是在稍后被调度</span>，到底何时操作被执行无法预先知晓，唯一能确定的是，操作被执行的<span style="background-color: #c0c0c0;">顺序得到保证</span>，先发起的操作肯定会先被执行。由于这个特征，不能从调用返回值中判断操作是否成功或结束，只能<span style="background-color: #c0c0c0;">注册某种类型的监听器</span>进行判断，Netty通过将返回值规定为ChannelFuture、Future来支持监听器（ChannnelFutureListener）的注册，监听器函数将在操作成功或者失败时得到通知。</p>
<div class="blog_h2"><span class="graybg">通道、事件、I/O</span></div>
<p>当一个<span style="background-color: #c0c0c0;">通道</span>注册到Netty后，会被<span style="background-color: #c0c0c0;">绑定到单个事件循环</span>，此事件循环对该通道的整个生命周期负责，<span style="background-color: #c0c0c0;">该通道的所有I/O操作都由事件循环对应的线程执行</span>。</p>
<p>多个通道可以共享单个事件循环，因此任何时候，<span style="background-color: #ff0000;"><span style="color: #ffffff;">代码都不应该使事件循环（的底层线程）被阻塞</span></span>（例如在通道处理器代码中执行数据库读写），这会严重影响Netty的性能。</p>
<div class="blog_h2"><span class="graybg">Bootstrapping</span></div>
<p>Bootstrapping分为两个类型：</p>
<ol>
<li>Bootstrap：用于客户端，或者任何数据报（UDP）通道（DatagramChannel）。具有一个事件循环组</li>
<li>ServerBootstrap：用于TCP服务器端，具有两个事件循环组（虽然可以指向一个实例），分别服务于用于监听的服务器通道本身、与客户端建立起来的通道。这种分开的方式能够在极高并发的场景下接受新的连接</li>
</ol>
<p>Netty允许使用单个事件循环组，同时负责接受连接、处理I/O，在很多应用场景下，这样做不会有什么问题。</p>
<div class="blog_h2"><span class="graybg">通道处理器和数据流</span></div>
<p>通道处理器具有统一的接口：ChannelHandler，主要可以分为两个子类型：ChannelInboundHandler、ChannelOutboundHandler。从数据流的角度更容易理解这两类处理器，所谓入站（Inbound）是指数据是从对端（Peer）流向本地用户程序，出站（Outbound）则反之。</p>
<p>通道处理器应当在Bootstrap阶段即注册，其在管道（ChannelPipeline）中的顺序决定了其操控数据的顺序。<span style="background-color: #c0c0c0;">管道的本质</span>就是一系列<span style="background-color: #c0c0c0;">排好序的通道处理器</span>。</p>
<p>管道中的处理器，按照顺序依次被调用以处理数据（前提是处理器支持对目标数据的处理，例如ChannelInboundHandler能处理入站数据），并可将转换完的数据传递给下一个处理器，直到管道的结尾（Tail）。例如下图的场景：</p>
<p><img class="aligncenter size-full wp-image-6490" src="https://blog.gmem.cc/wp-content/uploads/2013/12/channelpipeline.jpg" alt="channelpipeline" width="509" height="162" /></p>
<p>入站消息处理流程：</p>
<ol>
<li>任何通过入站事件（例如Read）进入管道的消息，会被管道中<span style="background-color: #c0c0c0;">第一个入站处理器</span>处理</li>
<li>第一个入站处理器可以处理此事件，或者什么都不做</li>
<li>第一个入站处理器将消息传递给下一个入站处理器</li>
<li>当管道中没有更多的入站处理器时，处理结束</li>
</ol>
<p>出站消息处理流程</p>
<ol>
<li>任何一个通过出站事件（例如Write）进入管道的消息，将从管道中<span style="background-color: #c0c0c0;">最后一个出站处理器</span>处理</li>
<li>……</li>
<li>当管道中没有更多出站处理器时，将出发实际的传输操作——例如通过套接字写入数据</li>
</ol>
<p>当通道处理器被加入管道时，它就得到一个通道处理器上下文（ChannelHandlerContext）对象，除非使用类似UDP的数据报协议，可以<span style="background-color: #c0c0c0;">安全的传递通道处理器上下文的引用</span>。<span style="background-color: #c0c0c0;">通道处理器上下文可以用来写入/发送消息</span>。直接将消息写入通道与通过通道处理器上下文写入消息的区别是：直接写入到通道，会导致消息从管道的尾部开始被处理；通过通道处理器上下文写入，则从该通道处理器的下一个处理器开始。</p>
<div class="blog_h2"><span class="graybg">编码、解码和领域逻辑</span></div>
<div class="blog_h3"><span class="graybg">Encode/Decode</span></div>
<p>Netty为通道处理器提供了一系列的适配器（Adapter），继承这些适配器类，只需要覆盖感兴趣的方法即可，其它的管道处理逻辑由父类提供。适配器类包括：ChannelHandlerAdapter、ChannelInboundHandlerAdapter、ChannelOutboundHandlerAdapter、ChannelDuplexHandlerAdapter。除了适配器类以外，Netty还提供了若干编码/解码类，用于方便的对消息进行编解码。</p>
<p>通过Netty进行消息收发时，需要进行编解码操作，因为只有字节才能在网络上传输：</p>
<ol>
<li>在接收消息时，需要将字节转换为Java对象，这是一个解码（Decode）过程。解码器都是ChannelInboundHandler的实现</li>
<li>在发送消息时，需要将Java对象转换为字节，这是一个编码（Encode）过程。编码器都是ChannelOutboundHandler的实现</li>
</ol>
<p>解码器实现类都会覆盖channelRead方法，在其中对数据进行解码，并调用ChannelHandlerContext.<span style="background-color: #c0c0c0;">fireChannelRead</span>(decodedMessage)，这导致管道中下一个处理器接手处理解码后的消息（decoded message）。编码器的执行过程类似。</p>
<div class="blog_h3"><span class="graybg">处理领域逻辑</span></div>
<p>大部分应用程序可能仅仅希望获得已经解码完毕的消息，并执行必要的领域逻辑，可以继承SimpleChannelInboundHandler&lt;T&gt;并覆盖其channelRead0(ChannelHandlerContext, T)方法，在其中实现领域逻辑。参数化类型T就是你期望处理的消息类型。从字节到T的转换是解码器需要完成的工作。</p>
<div class="blog_h1"><span class="graybg">传输机制（Transports）</span></div>
<p>网络应用都需要应用某种传输机制在网络上传送（Transfer）字节数据，传输机制可以是阻塞的/非阻塞的，也可以有多种实现方式，例如TCP、UDP，Netty进行了很好的抽象，当需要切换一种传输机制时，已编写的代码不需要做太多的改动。</p>
<div class="blog_h2"><span class="graybg">Transport API</span></div>
<p>下图展现了通道（Channel）类的层次结构与依赖关系：</p>
<p><img class="aligncenter size-full wp-image-6503" src="https://blog.gmem.cc/wp-content/uploads/2013/12/ChannelHierarchy.jpg" alt="ChannelHierarchy" width="600" height="242" /></p>
<p>可以看到，一个Channel持有一个ChannelPipeline、一个ChannelConfig。</p>
<p>ChannelConfig包含了通道的全部配置项信息，并且可以<span style="background-color: #c0c0c0;">按需随时修改</span>。通常每种传输都有自己特殊的配置信息，因此ChannelConfig被实现为多种子类型。</p>
<p>ChannelPipeline在前面简单的介绍过，其包含了若干ChannelHandler组成的链条。ChannelPipeline实现了拦截过滤器模式（Intercepting Filter Pattern）。ChannelPipeline也支持按需即时修改，可以动态的添加/删除ChannelHandler以实现高度灵活的应用程序。</p>
<p>Channel本身也提供了很多方法，例如：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">方法 </td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>eventLoop()</td>
<td>返回该通道关联的事件循环</td>
</tr>
<tr>
<td>alloc()</td>
<td>返回此通道使用的缓冲分配器</td>
</tr>
<tr>
<td>attr()</td>
<td>返回一个通道属性对象（Attribute），返回值绝不为null，但是对其调用get()可能返回null</td>
</tr>
<tr>
<td>pipeline()</td>
<td>返回该通道的管道 </td>
</tr>
<tr>
<td>isActive()</td>
<td>判断通道是否是激活的（即连接到对端）</td>
</tr>
<tr>
<td>localAddress()</td>
<td>获取通道本端地址</td>
</tr>
<tr>
<td>remoteAddress()</td>
<td>获取通道对端地址</td>
</tr>
<tr>
<td>write()</td>
<td>写入数据给对端，数据将通过ChannelPipeline被处理，例如：<br />
<pre class="crayon-plain-tag">Channel channel = ...;
ByteBuf buf = Unpooled.copiedBuffer( "Hello", CharsetUtil.UTF_8 );
ChannelFuture cf = channel.write( buf );
cf.addListener( new ChannelFutureListener() {

    @Override
    public void operationComplete( ChannelFuture future )
    {
        if ( future.isSuccess() )
        {
        }
        else
        {
            future.cause().printStackTrace();
        }
    }
} );</pre>
</td>
</tr>
</tbody>
</table>
<p>需要注意的是，<span style="background-color: #c0c0c0;">Channel类是线程安全的</span>，这意味着可以通过多个线程不加保护的访问同一Channel实例，在应用程序中多处传递Channel的实例，在需要时立刻通过它向对端发送消息是允许的，并且<span style="background-color: #c0c0c0;">发送的顺序得到保证</span>。</p>
<div class="blog_h2"><span class="graybg">内置的传输实现</span></div>
<p>Netty已经包含了若干内置的Channel实现，这些实现均支持全部的协议类型：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 80px; text-align: center;"> 名称</td>
<td style="text-align: center;">包</td>
<td style="text-align: center;">说明</td>
</tr>
</thead>
<tbody>
<tr>
<td>NIO</td>
<td>io.netty.channel.socket.nio</td>
<td>基于java.nio.channels构建，支持Selector操作。适用于高并发场景</td>
</tr>
<tr>
<td>OIO</td>
<td>io.netty.channel.socket.oio</td>
<td>基于java.net package构建，使用阻塞的流方式处理I/O。适用于低连接数、极低延迟场景</td>
</tr>
<tr>
<td>Local</td>
<td>io.netty.channel.local</td>
<td>在VM内部使用，通过管道进行通信。该传输与NIO一样，是完全异步的。服务器/客户端必须同时使用该传输。</td>
</tr>
<tr>
<td>Embedded</td>
<td>io.netty.channel.embedded</td>
<td>可以用于测试新的ChannelHandler实现。该通道不需要真实的网络支持</td>
</tr>
</tbody>
</table>
<div class="blog_h1"><span class="graybg">缓冲（Buffers）</span></div>
<p>每当需要传输数据的时候，必然牵涉到缓冲。出于性能优化、易用性的考虑，Netty没有使用Java NIO自带的Buffer实现，Netty提供的ByteBuf相当于NIO的ByteBuffer。</p>
<div class="blog_h2"><span class="graybg">Buffer API</span></div>
<p>Netty的缓冲API包含两个接口：ByteBuf、ByteBufHolder。</p>
<p>Netty使用<span style="background-color: #c0c0c0;">引用计数</span>（reference-counting）机制来确定何时<span style="background-color: #c0c0c0;">缓冲</span>及其申请的内存资源可以被安全的释放，该机制有利于提高运行速度、保持内存使用量在一个合理的级别。</p>
<p>Netty的缓冲API具有以下优点：</p>
<ol>
<li>如果必要，可以定义自己的缓冲类型</li>
<li>通过内置的复合缓冲类型，实现透明的零（内存）拷贝</li>
<li>缓冲容量按需自动扩展，就像StringBuffer一样</li>
<li>不需要调用flip()来切换读写模式，因为读写指针被分开</li>
<li>支持链式方法调用</li>
<li>基于引用计数</li>
<li>支持池化（Pooling）</li>
</ol>
<div class="blog_h2"><span class="graybg">字节容器：ByteBuf</span></div>
<p>通过ByteBuf，可以方便高效的添加、读取字节。为了方便读写，ByteBuf引入两个索引（指针），分别用于指示读、写的位置，ByteBuf允许进行顺序读，然后再跳回去继续读，你只需要调整读索引即可。</p>
<p>当数据被写入ByteBuf后，writerIndex增加相应的字节数。当执行read操作时，readerIndex增加，当readerIndex增大到writerIndex时，ByteBuf变为不可读，此时在进行read会导致IndexOutOfBoundsException。调用ByteBuf的任何<span style="background-color: #c0c0c0;">read*、write*</span>方法均会<span style="background-color: #c0c0c0;">导致索引增加</span>，相反的<span style="background-color: #c0c0c0;">set*、get*不会移动索引</span>值。</p>
<p>ByteBuf具有可选的最大容量（默认Integer.MAX_VALUE），尝试超过此容量限制进行写入会触发异常。</p>
<div class="blog_h3"><span class="graybg">不同类型的ByteBuf</span></div>
<p>使用Netty时，你可能遇到3种不同类型的ByteBuf：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">类型 </td>
<td style="text-align: center;">说明</td>
</tr>
</thead>
<tbody>
<tr>
<td>堆缓冲</td>
<td>
<p>最常见的类型，直接在Java堆中存储的缓冲类型，背后使用数组实现（hasArray返回true），在不使用缓冲池的情况下，该类型分配、回收的速度较快。通过非堆缓冲来访问array()方法会导致UnsupportedOperationException</p>
</td>
</tr>
<tr>
<td>直接缓冲 </td>
<td>所谓直接，是指在堆外，也就是物理机器上直接分配内存。直接缓冲之所以优化，是因为避免了一次内存拷贝（JVM在发送数据到Socket时，会将堆缓冲拷贝到直接内存）。直接缓冲的缺点是，分配、回收的代价比堆缓冲大。Netty用缓冲池来规避这一缺陷</td>
</tr>
<tr>
<td>组合缓冲</td>
<td>
<p>可以组合多个ByteBuf的实例，并且提供一个高层的视图。例如现代应用的消息经常被分为Head、Body两部分，有时候只需要修改Head，相同的Body可以发给不同的客户端，这种情况下组合缓冲可以减少内存拷贝。</p>
<p>相比之下，使用JDK的ByteBuffer无法达到此效果，只能创建一个新的、大的缓冲，将被组合的缓冲逐个拷贝进来</p>
<p>使用Netty的组合缓冲来实现分散/聚集，不会遇到NIO分散/聚集的性能问题</p>
</td>
</tr>
</tbody>
</table>
<div class="blog_h2"><span class="graybg">ByteBuf支持的操作</span></div>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">操作</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>随机访问</td>
<td>指定一个index，可以进行读、写。支持读写字节、字节数组、字符、布尔等类型。这类操作不会修改读写索引，包括一系列的get/set方法</td>
</tr>
<tr>
<td>顺序访问</td>
<td>
<p>与上面类似，但是会移动读写索引，包括一系列的read/write方法。数据类型长度如下：</p>
<p>1　Boolean, Byte, UnsignedByte<br />2　UnsignedShort<br />3　Medium, UnsignedMedium<br />4　Int, UnsignedInt<br />8　Long, UnsignedLong</p>
</td>
</tr>
<tr>
<td>丢弃字节</td>
<td>方法discardReadBytes()可以丢弃已经被读取过的字节。该方法会导致内存拷贝，因为需要向前移动尚未被读取的字节，以便腾出空间供写入</td>
</tr>
<tr>
<td>是否可读写</td>
<td>isReadable()、isWritable() 用于判断是否可读写（至少1字节）</td>
</tr>
<tr>
<td>可读写字节数</td>
<td>readableBytes()、writableBytes()用来计算当前缓冲中可读写的字节数</td>
</tr>
<tr>
<td>获取容量</td>
<td>capacity()获取当前容量；maxCapacity()获取最大容量</td>
</tr>
<tr>
<td>清空</td>
<td>clear()会把readerIndex、writerIndex都设置为0，但并不修改缓冲中的内容。该方法的语义与JDK的ByteBuffer.clear()不同。这是一个很廉价的操作</td>
</tr>
<tr>
<td>搜索操作</td>
<td>
<p>indexOf()可以用来搜索某个字节的出现位置，更复杂的搜索可以使用ByteBufProcessor</p>
<p>bytesBefore()可以用来轻松的判断某个字符的位置，例如NULL字符</p>
</td>
</tr>
<tr>
<td>标记与重置</td>
<td>
<p>readerIndex()、writerIndex()可以标记或返回当前的读写索引位置。resetReaderIndex()、resetWriterIndex()则可以重置</p>
</td>
</tr>
<tr>
<td>导出的ByteBuf</td>
<td>
<p>以下方法可以获得某个ByteBuf的视图：duplicate()、slice()、slice(int, int)、readOnly()、order(ByteOrder)。导出的ByteBuf具有独立的读、写、标记索引。这些视图与底层ByteBuf共享数据结构</p>
</td>
</tr>
<tr>
<td>拷贝ByteBuf</td>
<td>
<p>copy()可以拷贝以生成一个全新的ByteBuf</p>
</td>
</tr>
<tr>
<td>数组</td>
<td>
<p>hasArray()判断底层是否为数组；array()返回底层数组</p>
</td>
</tr>
<tr>
<td>引用计数</td>
<td>
<p>与引用计数相关的方法来自接口：ReferenceCounted</p>
<p>retain：将引用计数增加1或者更多数目<br />refCnt：获取当前引用计数<br />release：将引用计数减少1或者更多数目，如果引用计数为0，则当前对象可被释放</p>
</td>
</tr>
</tbody>
</table>
<div class="blog_h2"><span class="graybg">工具类</span></div>
<div class="blog_h3"><span class="graybg">ByteBufAllocator</span></div>
<p>该工具类可以方便的分配ByteBuf对象ChannelHandlerContext、Channel的alloc()方法，可以获得该工具类的实例。</p>
<p>目前Netty提供了两个ByteBufAllocator实现：</p>
<ol>
<li>PooledByteBufAllocator：其中一个使用类似于jemalloc的算法，实现了ByteBuf的池，该实现最小化了分配/回收内存的开销以及内存碎片。Netty默认使用该实现</li>
<li>UnpooledByteBufAllocator：每次都是创建全新的ByteBuf实例，不进行池化处理</li>
</ol>
<p>通过ChannelConfig可以很容易的切换上述两种实现。</p>
<p>ByteBufAllocator提供以下方法：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">方法</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>buffer()</td>
<td>根据实现，自动分配堆或者直接缓冲</td>
</tr>
<tr>
<td>heapBuffer()</td>
<td>分配堆缓冲 </td>
</tr>
<tr>
<td>directBuffer()</td>
<td>分配直接缓冲</td>
</tr>
<tr>
<td>compositeBuffer()</td>
<td>分配组合缓冲，类似方法：heapCompositeBuffer()、directCompositeBuffer()</td>
</tr>
<tr>
<td>ioBuffer()</td>
<td>返回一个用于从套接字读取数据的缓冲</td>
</tr>
</tbody>
</table>
<div class="blog_h3"><span class="graybg">Unpooled</span></div>
<p>该类提供了一些静态方法，用来方便的创建ByteBuf：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;"> 方法</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>buffer()</td>
<td>创建一个非池化的堆缓冲</td>
</tr>
<tr>
<td>directBuffer()</td>
<td>创建一个非池化的直接缓冲</td>
</tr>
<tr>
<td>wrappedBuffer()</td>
<td>返回一个ByteBuf，其包装了既有数据</td>
</tr>
<tr>
<td>copiedBuffer()</td>
<td>返回一个ByteBuf，其拷贝了既有数据</td>
</tr>
</tbody>
</table>
<div class="blog_h3"><span class="graybg">ByteBufUtil</span></div>
<p>包含了一些常用的功能。</p>
<div class="blog_h1"><span class="graybg">通道处理器（ChannelHandler）</span></div>
<p>通道处理器可以：</p>
<ol>
<li>处理消息格式转换</li>
<li>获取异常通知并处理</li>
<li>当通道激活/失活时得到通知</li>
<li>当通道从事件循环注册/解除注册时得到通知</li>
<li>处理用户定义事件</li>
</ol>
<div class="blog_h2"><span class="graybg">管道（ChannelPipeline）</span></div>
<p>管道维持了通道处理器的列表，其实现了一种高级形式的拦截过滤器，允许： </p>
<ol>
<li>控制事件的处理方式</li>
<li>控制不同通道处理器的交互方式</li>
</ol>
<p>对于每一个<span style="background-color: #c0c0c0;">新创建的通道，一个全新的ChannelPipeline</span>被创建，并且附到通道上，一旦此关联关系建立，在通道的生命周期内均不可以解除。</p>
<p>对于入站数据，将从管道的头部进入，依次由各ChannelHandler处理；对于出站数据，则由管道的尾部进入。管道会判断ChannelHandler的类型，它不会让ChannelInboundHandler去处理出站数据。</p>
<p>管道提供了以下方法：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 200px; text-align: center;">方法</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>addFirst() </td>
<td>添加ChannelHandler到管道头部</td>
</tr>
<tr>
<td>addBefore()</td>
<td>添加ChannelHandler到某个处理器前面 </td>
</tr>
<tr>
<td>addAfter()</td>
<td>添加ChannelHandler到某个处理器后面</td>
</tr>
<tr>
<td>addLast()</td>
<td>添加ChannelHandler到管道尾部</td>
</tr>
<tr>
<td>remove()</td>
<td>从管道中移除一个处理器</td>
</tr>
<tr>
<td>replace()</td>
<td>替换管道中的一个处理器</td>
</tr>
<tr>
<td>get()</td>
<td>获取管道中的某个ChannelHandler</td>
</tr>
<tr>
<td>context()</td>
<td>获取管道中的某个ChannelHandler的ChannelHandlerContext</td>
</tr>
<tr>
<td>contains()</td>
<td>判断管道中是否包含指定名称/类型的ChannelHandler</td>
</tr>
<tr>
<td>names()</td>
<td>返回所有ChannelHandler的名称的集合</td>
</tr>
<tr>
<td>iterator()</td>
<td>返回所有ChannelHandler的迭代器</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2">入站操作</td>
</tr>
<tr>
<td>fireChannelRegistered()</td>
<td>导致调用管道中下一个ChannelInboundHandler的channelRegistered被调用</td>
</tr>
<tr>
<td>fireChannelUnregistered() </td>
<td>导致调用管道中下一个ChannelInboundHandler的channelUnregistered被调用 </td>
</tr>
<tr>
<td>fireChannelActive()</td>
<td>导致调用管道中下一个ChannelInboundHandler的channelActive被调用</td>
</tr>
<tr>
<td>fireChannelInactive()</td>
<td>导致调用管道中下一个ChannelInboundHandler的channelInactive被调用</td>
</tr>
<tr>
<td>fireExceptionCaught()</td>
<td>导致调用管道中下一个ChannelInboundHandler的exceptionCaught被调用</td>
</tr>
<tr>
<td>fireUserEventTriggered()</td>
<td>导致调用管道中下一个ChannelInboundHandler的userEventTriggered被调用</td>
</tr>
<tr>
<td>fireChannelRead() </td>
<td>导致调用管道中下一个ChannelInboundHandler的channelRead被调用</td>
</tr>
<tr>
<td>fireChannelReadComplete() </td>
<td>导致调用管道中下一个ChannelInboundHandler的channelReadComplete被调用</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2">出站操作</td>
</tr>
<tr>
<td>bind()</td>
<td>请求将Channel绑定到一个本地地址。导致调用下一个ChannelOutboundHandler的bind(ChannelHandlerContext, SocketAddress, ChannelPromise)方法</td>
</tr>
<tr>
<td>connect()</td>
<td>请求将Channel连接到一个远程地址。导致调用下一个ChannelOutboundHandler的connect(ChannelHandlerContext, SocketAddress,<br />ChannelPromise)</td>
</tr>
<tr>
<td>disconnect()</td>
<td>请求断开通道的连接，导致调用下一个ChannelOutboundHandler的disconnect(ChannelHandlerContext, ChannelPromise)</td>
</tr>
<tr>
<td>close()</td>
<td>请求关闭通道，导致调用下一个ChannelOutboundHandler的close(ChannelHandlerContext, ChannelPromise)</td>
</tr>
<tr>
<td>deregister()</td>
<td>请求从事件循环中解除当前通道的注册，导致调用下一个ChannelOutboundHandler的deregister(ChannelHandlerContext, ChannelPromise)</td>
</tr>
<tr>
<td>flush()</td>
<td>请求刷空提到所有未决的写操作，导致调用下一个ChannelOutboundHandler的flush(ChannelHandlerContext)被调用</td>
</tr>
<tr>
<td>write()</td>
<td>请求写入指定的数据到通道中，导致调用下一个ChannelOutboundHandler的write(ChannelHandlerContext, Object msg, ChannelPromise)</td>
</tr>
<tr>
<td>writeAndFlush()</td>
<td>请求写入并刷空，导致调用下一个ChannelOutboundHandler的writeAndFlush()被调用</td>
</tr>
<tr>
<td>read()</td>
<td>请求从通道中读取更多的数据，导致调用下一个ChannelOutboundHandler的read(ChannelHanlderContext)</td>
</tr>
</tbody>
</table>
<p>举例：</p>
<pre class="crayon-plain-tag">ChannelPipeline pipeline = ..;
FirstHandler firstHandler = new FirstHandler();
pipeline.addLast("handler1", firstHandler);
pipeline.addFirst("handler2", new SecondHandler());
pipeline.addLast("handler3", new ThirdHandler());

pipeline.remove("handler3");
pipeline.remove(firstHandler); 
pipeline.replace("handler2", "handler4", new FourthHandler());</pre>
<p>本文在前面提到过，绝不要在I/O线程中阻塞，否则将影响使用当前事件循环的所有通道的性能。但是<span style="background-color: #c0c0c0;">有些时候阻塞操作必然的</span>，比如需要进行JDBC操作。为了解决这个矛盾，Netty为所有ChannelPipeline.add*方法提供了一个可选的参数<span style="background-color: #c0c0c0;">EventExecutorGroup</span>。该参数用于<span style="background-color: #c0c0c0;">执行ChannelHandler定义的方法</span>。</p>
<div class="blog_h2"><span class="graybg">ChannelHandlerContext</span></div>
<p>一旦某个ChannelHandler被添加到管道中，一个<span style="background-color: #c0c0c0;">新的通道处理器上下文（ChannelHandlerContext）被创建并关联到ChannelHandler，并永远不会被替换</span>。此上下文允许当前处理器与其它处理器进行交互。</p>
<p>ChannelHandlerContext包含很多与ChannelPipeline、Channel相同签名的方法，其区别是：<span style="background-color: #c0c0c0;">通过Channel/ChannelPipeline调用这些方法，会穿过整个管道</span>；而<span style="background-color: #c0c0c0;">通过ChannelHandlerContext调用，只会从当前处理器出发</span>穿越剩余的管道部分。下面是用法示例：</p>
<pre class="crayon-plain-tag">ChannelHandlerContext ctx = getChannelHandlerContext();
//发起一个从管道尾部贯穿管道的写（出站）事件
Channel channel = ctx.channel();
channel.write( Unpooled.copiedBuffer( "Hello", CharsetUtil.UTF_8 ) );
//另外一种写法
ChannelPipeline pipeline = ctx.pipeline();
pipeline.write( Unpooled.copiedBuffer( "Hello", CharsetUtil.UTF_8 ) );

//直接使用通道处理器上下文：
ctx.write( Unpooled.copiedBuffer( "Hello", CharsetUtil.UTF_8 ) );</pre>
<p>前两个写入与第三个写入的差异，可以参考下图理解：</p>
<p><img class="aligncenter size-full wp-image-6526" src="https://blog.gmem.cc/wp-content/uploads/2013/12/diff-approach-of-write.jpg" alt="diff-approach-of-write" width="95%" />在ChannelHandler外面使用ChannelHandlerContext也是可以的，后者是线程安全的。</p>
<p>需要注意的是，包含了<pre class="crayon-plain-tag">@Sharable</pre> 注解的ChannelHandler类的<span style="background-color: #c0c0c0;">同一个实例会被添加到不同的管道</span>（即被多个Channel共享）中。如果尝试将没有@Sharable注解的同一实例添加到不同的管道，会抛出异常。使用这种共享的处理器时最好保证其是无状态的。</p>
<div class="blog_h2"><span class="graybg">通道状态模型</span></div>
<p>Netty引入了一个简单的状态模型来描述通道的生命周期，ChannelInboundHandler的方法映射到这些状态上：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 25%; text-align: center;">状态</td>
<td style="text-align: center;">描述 </td>
</tr>
</thead>
<tbody>
<tr>
<td>channelUnregistered</td>
<td>通道已经建立，但尚未注册到事件循环</td>
</tr>
<tr>
<td>channelRegistered </td>
<td>通道已经注册到事件循环</td>
</tr>
<tr>
<td>channelActive</td>
<td>通道已经激活，意味着已经与对端连接成功，可以收发数据</td>
</tr>
<tr>
<td>channelInactive</td>
<td>通道没有连接到对端</td>
</tr>
</tbody>
</table>
<p>通常情况下，通道的生命周期是由上表的四个状态顺序组成。在某些高级应用场景下，可能临时解除注册以暂停事件处理，这时就会有多于一个的注册/解除注册状态出现。不论如何，激活/失活状态只会出现一次，分别代表了连接的打开和关闭，如果需要在关闭后继续与对端通信，必须重新创建通道。</p>
<div class="blog_h2"><span class="graybg">不同类型的通道处理器</span></div>
<p>本文前面已经提到过，通道处理器分为两类：入站、出站，它们的功能划分如下：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 25%; text-align: center;">处理器 </td>
<td style="text-align: center;">功能 </td>
</tr>
</thead>
<tbody>
<tr>
<td>入站（Inbound）处理器</td>
<td>处理所有入站数据（接收到的数据）、以及所有的通道状态变更</td>
</tr>
<tr>
<td>出站（Outbound）处理器</td>
<td>处理所有出站数据（准备发出的数据）、并且允许拦截各种操作 </td>
</tr>
</tbody>
</table>
<p>处理器共同的父接口ChannelHandler提供了以下方法（这些方法都将ChannelHandlerContext作为一个参数）：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 25%; text-align: center;">方法</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>handlerAdded()</td>
<td>当处理器被添加到管道时，该方法被调用</td>
</tr>
<tr>
<td>handlerRemoved()</td>
<td>当处理器被从管道移除时，该方法被调用</td>
</tr>
<tr>
<td>exceptionCaught()</td>
<td>当执行处理时，发生异常时调用</td>
</tr>
</tbody>
</table>
<div class="blog_h3"><span class="graybg">Inbound handlers</span></div>
<p>ChannelInboundHandler提供了一系列的方法，当通道的生命周期状态改变、或数据抵达时，会自动调用：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 25%; text-align: center;">方法 </td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>channelRegistered()</td>
<td>一旦某个通道被注册到事件循环，即调用</td>
</tr>
<tr>
<td>channelUnregistered() </td>
<td>一旦通道从事件循环解除注册，即调用</td>
</tr>
<tr>
<td>channelActive()</td>
<td>一旦通道变为活动的，即连接到对端，或者绑定监听完毕后，即调用</td>
</tr>
<tr>
<td>channelInactive()</td>
<td>一旦通道与对端的连接断开，即调用</td>
</tr>
<tr>
<td>channelReadComplete()</td>
<td>一旦读操作执行完毕，即调用</td>
</tr>
<tr>
<td>channelRead()</td>
<td>一旦入站缓冲包含可读数据时，即调用</td>
</tr>
<tr>
<td>userEventTriggered()</td>
<td>用户自定义事件被触发时调用</td>
</tr>
</tbody>
</table>
<p>ChannelInboundHandlerAdapter类提供了ChannelInboundHandler的缺省适配，这些<span style="background-color: #c0c0c0;">缺省适配的行为都是：转到下一个处理器继续处理</span>。</p>
<p>需要注意的是，你<span style="background-color: #c0c0c0;">覆盖的channelRead()方法要对缓冲的释放负责</span>，特别在使用ByteBuf缓冲池的情况下，忘记释放（release）资源会导致内存泄漏。下面的例子展示了如何丢弃入站消息并进行资源释放：</p>
<pre class="crayon-plain-tag">@Sharable
public class DiscardInboundHandler extends ChannelInboundHandlerAdapter
{
    private boolean discard = true;
    @Override
    public void channelRead( ChannelHandlerContext ctx, Object msg )
    {
        //只要不调用ctx.fireChannelRead，就相当于丢弃了该消息，后续的处理器不会对其进行处理
        //对于丢弃的消息，应当释放其资源
        if ( discard ) ReferenceCountUtil.release( msg );
        else ctx.fireChannelRead( msg );
    }
}</pre>
<p>如果存在资源忘记释放的情况，Netty会以WARN级别的日志发出警告。手工进行资源的释放是比较琐碎的工作，<span style="background-color: #c0c0c0;">继承SimpleChannelInboundHandler类并覆盖channelRead0则不必手工释放</span>。如果使用SimpleChannelInboundHandler，处理完毕后消息就被自动释放，<span style="background-color: #c0c0c0;">不能保留消息的引用供后续使用</span>。SimpleChannelInboundHandler对channelRead方法覆盖如下：</p>
<pre class="crayon-plain-tag">@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    boolean release = true;
    try {
        if (acceptInboundMessage(msg)) {
            //如果msg的类型与SimpleChannelInboundHandler泛型参数的类型匹配，才进行处理
            //前面的通道处理器应当已经将原始的ByteBuf转换为期望的消息类型
            @SuppressWarnings("unchecked")
            I imsg = (I) msg;
            //调用channelRead0对消息进行处理
            channelRead0(ctx, imsg);
        } else {
            //如果类型不匹配，则当前处理器不做任何操作，将其原封不动的传递给下一个处理器
            release = false;
            ctx.fireChannelRead(msg);
        }
    } finally {
        //如果当前处理器配置了自动释放，并且对消息进行了处理，释放之
        if (autoRelease &amp;&amp; release) {
            ReferenceCountUtil.release(msg);
        }
    }
}</pre>
<div class="blog_h3"><span class="graybg">Outbound handlers</span></div>
<p>ChannelOutboundHandler提供了以下方法：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">方法</td>
<td style="text-align: center;">说明</td>
</tr>
</thead>
<tbody>
<tr>
<td>bind()</td>
<td>一旦请求绑定到本地地址，即调用此方法</td>
</tr>
<tr>
<td>connect()</td>
<td>一旦请求连接到对端，即调用此方法</td>
</tr>
<tr>
<td>disconnect()</td>
<td>一旦请求对端断开连接，即调用此方法</td>
</tr>
<tr>
<td>close()</td>
<td>一旦请求关闭通道，即调用此方法</td>
</tr>
<tr>
<td>deregister()</td>
<td>一旦请求从事件循环解除当前通道的注册，即调用此方法</td>
</tr>
<tr>
<td>read()</td>
<td>一旦请求从通道读取更多数据，即调用此方法 </td>
</tr>
<tr>
<td>flush()</td>
<td>一旦请求刷空数据发往对端，即调用此方法</td>
</tr>
<tr>
<td>write()</td>
<td>一旦请求写入数据到通道，即调用此方法</td>
</tr>
</tbody>
</table>
<p>几乎上表的全部方法要求一个ChannelPromise类型的参数，一旦请求停止继续在管道中前进时，应当调用ChannelPromise进行通知。</p>
<p>ChannelOutboundHandlerAdapter类提供了ChannelOutboundHandler的确省适配，它的实现都是调用ChannelHandlerContext的同名方法，将事件转给管道中下一个处理器处理。再次强调一下，下一个是指<span style="background-color: #c0c0c0;">更靠近管道头部的</span>、离当前处理器最近的出站处理器。下面的例子展示了如何丢弃出站消息并进行资源释放：</p>
<pre class="crayon-plain-tag">@Sharable
public class DiscardOutboundHandler extends ChannelOutboundHandlerAdapter
{
    private boolean discard = true;
    @Override
    public void write( ChannelHandlerContext ctx, Object msg, ChannelPromise promise )
    {
        if ( discard )
        {
            //只要不调用ctx.write，就相当于丢弃了消息，后续处理器不会对其进行处理，数据也不会发送到对端
            //对于丢弃的消息，应当释放其资源
            ReferenceCountUtil.release( msg );
            //必须通知ChannelPromise已经完成对消息的处理，否则调用channel.write时给出的ChannelFutureListener
            //不会被调用
            promise.setSuccess();
        }
        else
        {
            ctx.write( msg );
        }
    }
}</pre>
<div class="blog_h2"><span class="graybg">ChannelOption</span></div>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 250px; text-align: center;">选项 </td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>ALLOCATOR</td>
<td>设置字节缓冲的分配器，设置该选项以修改缓冲区的分配方式 </td>
</tr>
<tr>
<td>RCVBUF_ALLOCATOR</td>
<td>设置用于接收缓冲的分配器</td>
</tr>
<tr>
<td>MESSAGE_SIZE_ESTIMATOR</td>
<td>设置消息长度估算器</td>
</tr>
<tr>
<td>CONNECT_TIMEOUT_MILLIS</td>
<td>连接超时时间</td>
</tr>
<tr>
<td>MAX_MESSAGES_PER_READ</td>
<td>单此读取时间最多从底层套接字读取的字节数</td>
</tr>
<tr>
<td>WRITE_SPIN_COUNT</td>
<td>向输出缓冲写入数据时，自旋（循环操作）的次数，如果再循环内操作完成则立即终止循环</td>
</tr>
<tr>
<td>WRITE_BUFFER_HIGH_WATER_MARK</td>
<td>写缓冲高水位，超过后Netty在内部标记一个不可写，直到水位降低到底水位以下</td>
</tr>
<tr>
<td>WRITE_BUFFER_LOW_WATER_MARK</td>
<td>写缓冲低水位，低于该水位后，Netty在内部标记一个可写 </td>
</tr>
<tr>
<td>ALLOW_HALF_CLOSURE</td>
<td>是否允许半关闭套接字</td>
</tr>
<tr>
<td>SO_BROADCAST</td>
<td>允许底层套接字发送广播数据报</td>
</tr>
<tr>
<td>SO_KEEPALIVE</td>
<td>启用TCP保活</td>
</tr>
<tr>
<td>SO_SNDBUF</td>
<td>给操作系统一个提示值，用来指示出站数据缓冲区的大小</td>
</tr>
<tr>
<td>SO_RCVBUF</td>
<td>操作系统接收数据时，使用的缓冲区大小</td>
</tr>
<tr>
<td>SO_REUSEADDR</td>
<td>启用套接字地址重用</td>
</tr>
<tr>
<td>SO_LINGER</td>
<td>影响关闭套接字的方式，设置一个徘徊时间，超过后立即丢弃发送队列中的数据并立即关闭</td>
</tr>
<tr>
<td>SO_BACKLOG</td>
<td>设置入站连接请求排队的数量，超过此数量的连接被拒绝</td>
</tr>
<tr>
<td>SO_TIMEOUT</td>
<td>阻塞的套接字操作的超时时间 </td>
</tr>
<tr>
<td>IP_TOS</td>
<td>设置服务类型（TOS）字段，可以指定最小延时、最大吞吐量、最高可靠性、最小成本</td>
</tr>
<tr>
<td>IP_MULTICAST_ADDR</td>
<td>设置用于多播的网络接口的地址。最终调用DatagramSocket.setInterface()</td>
</tr>
<tr>
<td>IP_MULTICAST_IF</td>
<td>对于多网络接口（Multihomed）主机，用于设置组播包的出口网卡。最终调用DatagramSocket.setNetworkInterface()</td>
</tr>
<tr>
<td>IP_MULTICAST_TTL</td>
<td>组播数据包的IP报文的TTL字段</td>
</tr>
<tr>
<td>IP_MULTICAST_LOOP_DISABLED</td>
<td>禁止本地环回的多播数据报</td>
</tr>
<tr>
<td>TCP_NODELAY</td>
<td>禁止TCP延迟确认算法</td>
</tr>
</tbody>
</table>
<div class="blog_h1"><span class="graybg">编解码工具（Codec）</span></div>
<p>当编写网络应用时，往往需要实现某种编解码工具。该工具用<span style="background-color: #c0c0c0;">完成原始字节到某种自定义消息格式的双向转换</span>。Codec一般由一个编码器、一个解码器组成，前者用于出站数据、后者用于入站数据。</p>
<p>编解码工具本身属于ChannelHandler。</p>
<div class="blog_h2"><span class="graybg">解码器（Decoders）</span></div>
<div class="blog_h3"><span class="graybg">ByteToMessageDecoder</span></div>
<p>这类解码器可以将字节转换为某种形式的消息，消息本身甚至也是字节格式的。抽象类ByteToMessageDecoder提供了以下方法：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">方法</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>decode() </td>
<td>该方法子类必须覆盖。用于将包含所有接收到的字节的ByteBuf进行解码，并将结果放入List中</td>
</tr>
<tr>
<td>decodeLast()</td>
<td>该方法仅仅会在通道变为inactive调用一次，如果需要特殊化处理，可以覆盖此方法</td>
</tr>
</tbody>
</table>
<p>考虑如下场景：对端发送一系列的字节过来，其中包含若干Integer类型的整数，本端需要把这些整数分离出来，<span style="background-color: #c0c0c0;">逐个的传递</span>给后面的ChannelHandler处理，如下图：</p>
<p><img class="aligncenter size-full wp-image-6547" src="https://blog.gmem.cc/wp-content/uploads/2013/12/ToIntegerDecoder.jpg" alt="ToIntegerDecoder" width="492" height="187" /></p>
<p>示意代码如下：</p>
<pre class="crayon-plain-tag">public class ToIntegerDecoder extends ByteToMessageDecoder
{
    @Override
    public void decode( ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out ) throws Exception
    {
        if ( in.readableBytes() &gt;= 4 )
        {
            out.add( in.readInt() );
        }
    }
}</pre>
<p>可以看到，上述decode方法只是对输入缓冲执行一次解码，尝试得到一个Integer，但如果输入缓冲中包含很多Integer，如何处理呢？ByteToMessageDecoder已经封装好循环调用deocde方法的逻辑：</p>
<pre class="crayon-plain-tag">protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out) {
    try {
        //如果输入缓冲可读，则循环处理
        while (in.isReadable()) {
            int outSize = out.size(); //解码结果列表的长度
            int oldInputLength = in.readableBytes(); //当前输入缓冲可读数
            decode(ctx, in, out); //调用子类实现的解码方法，执行解码

            if (ctx.isRemoved()) {
                break;
            }
            //如果解码前后，结果列表长度没有变化、并且输入长度也没有变化
            //说明当前的输入缓冲尚不够解码下一个消息，因此需要退出循环
            if (outSize == out.size()) {
                if (oldInputLength == in.readableBytes()) {
                    break;
                } else {
                    continue;
                }
            }
            //结果列表增加了，但是输入缓冲没有消耗，这是非法的，抛出异常
            if (oldInputLength == in.readableBytes()) {
                throw new DecoderException(
                        StringUtil.simpleClassName(getClass()) +
                        ".decode() did not read anything but decoded a message.");
            }
            //如果只解码一次，那么不作循环处理
            if (isSingleDecode()) {
                break;
            }
        }
    } catch (DecoderException e) {
        throw e;
    } catch (Throwable cause) {
        throw new DecoderException(cause);
    }
}</pre>
<p>解码过程执行完毕后，如何将结果列表依次发送给下一个ChannelHandler处理呢？这个逻辑也由ByteToMessageDecoder实现了：</p>
<pre class="crayon-plain-tag">public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (msg instanceof ByteBuf) {
        //构建解码输出列表，Netty使用了私有的ArrayList子类，主要是出于性能方面的考虑
        RecyclableArrayList out = RecyclableArrayList.newInstance();
        try {
            ByteBuf data = (ByteBuf) msg;
            first = cumulation == null;
            if (first) {
                //如果是第一次解码，将累积缓冲（cumulation）设置为当前输入缓冲
                cumulation = data;
            } else {
                //否则，将上次没解码完的多余数据和本次接收到的数据累加起来，作为累积缓冲
                //由于TCP的特征，数据可能呈碎片化到达，因此某一次channelRead过程中遇到无法解码的结尾部分是很常见的
                cumulation = cumulator.cumulate(ctx.alloc(), cumulation, data);
            }
            //循环的进行解码
            callDecode(ctx, cumulation, out);
        } catch (DecoderException e) {
            throw e;
        } catch (Throwable t) {
            throw new DecoderException(t);
        } finally {
            //即使有异常抛出，也会调用后面的处理器
            
            //如果累积缓冲没有数据，将其回收
            if (cumulation != null &amp;&amp; !cumulation.isReadable()) {
                cumulation.release();
                cumulation = null;
            }
            int size = out.size();
            //遍历解码结果，逐个交由下游处理器处理
            for (int i = 0; i &lt; size; i ++) {
                ctx.fireChannelRead(out.get(i));
            }
            out.recycle();
        }
    } else {
        //如果输入消息不是ByteBuf，那么当前解码器不能处理，交由下一个ChannelHandler处理
        ctx.fireChannelRead(msg);
    }
}</pre>
<div class="blog_h3"><span class="graybg">ReplayingDecoder</span></div>
<p>该类型是ByteToMessageDecoder的一种特殊形式，主要解决难以预先（除非读取到结尾）知晓输入缓冲中是否还有足够的数据供解码（下一个输出）的问题，继承该类型不需要进行预读判断：</p>
<pre class="crayon-plain-tag">public class ToIntegerDecoder extends ReplayingDecoder&lt;Void&gt;
{
    @Override
    public void decode( ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out ) throws Exception
    {
        //前面不需要判断输入缓冲是否有足够4字节
        //如果读取失败，一个特殊的Signal错误被抛出，ReplayingDecoder会自动处理并终止解码循环
        out.add( in.readInt() );

    }
}</pre>
<p>以下是ReplayingDecoder的核心代码，可以看到它利用一个ReplayingDecoderBuffer来装饰输入缓冲，ReplayingDecoderBuffer会在执行读取方法时进行检查，检查失败时（不能读取）会抛出一个Signal，ReplayingDecoder捕获此信号，将输入缓冲的读索引回滚到检查点上</p>
<pre class="crayon-plain-tag">//一个专用的ByteBuf子类，用于实现“回放”（重新读取）
private final ReplayingDecoderBuffer replayable = new ReplayingDecoderBuffer();
    
@Override
protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List&lt;Object&gt; out) {
    replayable.setCumulation(in); //包裹原始输入以支持回放
    try {
        while (in.isReadable()) {
            int oldReaderIndex = checkpoint = in.readerIndex();
            int outSize = out.size();
            //泛型参数通常是一个枚举类型，如果不需要状态管理，则使用Void作为泛型参数
            S oldState = state;
            int oldInputLength = in.readableBytes();
            try {
                //解码时需要调用缓冲replayable的方法，该类的读取方法在无法读出请求的数据时会抛出Signal
                decode(ctx, replayable, out);
                if (ctx.isRemoved()) {
                    break;
                }
                if (outSize == out.size()) {
                    //输出结果未增加
                    if (oldInputLength == in.readableBytes() &amp;&amp; oldState == state) {
                        throw new DecoderException(
                                StringUtil.simpleClassName(getClass()) + ".decode() must consume the inbound " +
                                "data or change its state if it did not decode anything.");
                    } else {
                        //数据已经被消耗，或者导致了状态变迁，可能需要继续往下读
                        //例如，我们使用NUL字符分隔消息，如果按字节读的话，可能多次执行到这里
                        continue;
                    }
                }
            } catch (Signal replay) {
                //尝试读取失败了
                replay.expect(REPLAY);
                if (ctx.isRemoved()) {
                    break;
                }
                //返回到检查点（checkpoint）
                int checkpoint = this.checkpoint;
                if (checkpoint &gt;= 0) {
                    in.readerIndex(checkpoint);//设置读索引
                } else {
                }
                break; //退出循环，不再继续解码，等待下一次事件驱动
            }
            //必须要消耗输入缓冲或者改变解码状态，否则说明程序有问题，可能无限循环
            if (oldReaderIndex == in.readerIndex() &amp;&amp; oldState == state) {
                throw new DecoderException(
                       StringUtil.simpleClassName(getClass()) + ".decode() method must consume the inbound data " +
                       "or change its state if it decoded something.");
            }
            if (isSingleDecode()) {
                break;
            }
        }
    } catch (DecoderException e) {
        throw e;
    } catch (Throwable cause) {
        throw new DecoderException(cause);
    }
}</pre>
<p>下面的代码是ReplayingDecoderBuffer的代码片段，可以看到它在各种读取方法执行前，进行了检查：</p>
<pre class="crayon-plain-tag">final class ReplayingDecoderBuffer extends ByteBuf {
    private static final Signal REPLAY = ReplayingDecoder.REPLAY; //单例异常类
    private ByteBuf buffer;  //被装饰的字节缓冲

    @Override
    public byte readByte() {
        checkReadableBytes(1);
        return buffer.readByte();
    }
    
    @Override
    public ByteBuf readBytes(byte[] dst, int dstIndex, int length) {
        checkReadableBytes(length);
        buffer.readBytes(dst, dstIndex, length);
        return this;
    }
    
    private void checkReadableBytes(int readableBytes) {
        //如果不可读（没有足够的字节数），抛出信号
        if (buffer.readableBytes() &lt; readableBytes) {
            throw REPLAY;
        }
    }
}</pre>
<div class="blog_h3"><span class="graybg">MessageToMessageDecoder</span></div>
<p>该类型是参数化的，其限定了输入消息的类型，至于输出什么类型不是该类关心的内容，其代码如下：</p>
<pre class="crayon-plain-tag">public abstract class MessageToMessageDecoder&lt;I&gt; extends ChannelInboundHandlerAdapter {

    private final TypeParameterMatcher matcher;
    protected MessageToMessageDecoder() {
        matcher = TypeParameterMatcher.find(this, MessageToMessageDecoder.class, "I");
    }
    public boolean acceptInboundMessage(Object msg) throws Exception {
        return matcher.match(msg);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        RecyclableArrayList out = RecyclableArrayList.newInstance();
        try {
            if (acceptInboundMessage(msg)) {
                //如果输入消息与当前类的参数类型匹配，则执行解码
                I cast = (I) msg;
                try {
                    decode(ctx, cast, out);
                } finally {
                    //如果接收输入，必须尝试释放输入消息
                    ReferenceCountUtil.release(cast);
                }
            } else {
                //否则，只是简单的将其加入到输出中
                out.add(msg);
            }
        } catch (DecoderException e) {
            throw e;
        } catch (Exception e) {
            throw new DecoderException(e);
        } finally {
            int size = out.size();
            for (int i = 0; i &lt; size; i ++) {
                ctx.fireChannelRead(out.get(i));
            }
            out.recycle();
        }
    }
    protected abstract void decode(ChannelHandlerContext ctx, I msg, List&lt;Object&gt; out) throws Exception;
}</pre>
<p>该类很巧妙的利用参数化类型实现了过滤器，事实上我们可以在管道中放入各种MessageToMessageDecoder的子类型，他们只会处理类型匹配的消息。通过把多个这样的解码器串联使用，可以实现复杂消息的解码，对逻辑进行分离以便重用。 </p>
<div class="blog_h2"><span class="graybg">编码器（Encoders）</span></div>
<div class="blog_h3"><span class="graybg">MessageToByteEncoder</span></div>
<p>这是一个参数化类型抽象类，用于将某种消息转换为字节缓冲（ByteBuf），消息的类型通过类型参数指定。该类提供以下方法：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">方法</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>encode()</td>
<td>处理出站消息，并将其转换为字节缓冲</td>
</tr>
</tbody>
</table>
<p>在解码器一节中，我们举了一个将输入缓冲解码为一个个整型的例子，这里我们将实现一个逆过程——将整型转换为字节流：</p>
<pre class="crayon-plain-tag">public class IntegerToByteEncoder extends MessageToByteEncoder&lt;Integer&gt;
{
    @Override
    public void encode( ChannelHandlerContext ctx, Integer msg, ByteBuf out ) throws Exception
    {
        out.writeInt( msg ); //将整数写入到输出缓冲
    }
}</pre>
<div class="blog_h3"><span class="graybg">MessageToMessageEncoder</span></div>
<p>该类也是一个参数化类型，也只有一个必须覆盖的方法：</p>
<pre class="crayon-plain-tag">protected abstract void encode(ChannelHandlerContext ctx, I msg, List&lt;Object&gt; out) throws Exception;</pre>
<p>可以看到，此编码器用于将一个输入消息编码为多个输出消息的列表。 </p>
<div class="blog_h2"><span class="graybg">Codec</span></div>
<p>有些时候需要实现编解码器对，并将其封装到一个类中，此时可以继承各种Codec类：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">Codec类 </td>
<td style="text-align: center;">说明</td>
</tr>
</thead>
<tbody>
<tr>
<td>ByteToByteCodec</td>
<td>在字节与字节之间进行编解码</td>
</tr>
<tr>
<td>ByteToMessageCodec</td>
<td>在字节与消息之间进行编解码</td>
</tr>
<tr>
<td>MessageToMessageCodec</td>
<td>在消息与消息之间进行编解码</td>
</tr>
</tbody>
</table>
<p>以上各种Codec类型都是ChannelDuplexHandler的子类，而后者：</p>
<pre class="crayon-plain-tag">public class ChannelDuplexHandler extends ChannelInboundHandlerAdapter implements ChannelOutboundHandler {}</pre>
<p>同时实现了入站、出站通道处理器接口，因此，Code类可以直接加入到ChannelPipeline中。</p>
<div class="blog_h1"><span class="graybg">使用内置通道处理器/编解码器</span></div>
<div class="blog_h2"><span class="graybg">使用SSL/TLS为Netty应用程序提供安全性</span></div>
<p>SSL/TLS为很多高层协议提供了安全支持，例如HTTPS、SMTPS。JDK提供了SslContext、SslEngine类对SSL提供支持，Netty继承了JDK的SSL组件并提供了额外的功能，使其易于被Netty应用程序使用。</p>
<p>通道处理器SslHandler用于处理与SSL相关的逻辑，通常可以使用ChannelInitializer来将此处理器加入到管道的头部，例如：</p>
<pre class="crayon-plain-tag">public class SslChannelInitializer extends ChannelInitializer&lt;Channel&gt;
{

    private final SSLContext context;
    //当进行SSL握手时，作为客户端还是服务器端
    private final boolean    client;
    //如果设置为真，第一次写请求不被SSLEngine加密
    private final boolean    startTls;

    public SslChannelInitializer( SSLContext context, boolean client, boolean startTls )
    {
        this.context = context;
        this.client = client;
        this.startTls = startTls;
    }

    @Override
    protected void initChannel( Channel ch ) throws Exception
    {
        //获取一个新的SSL引擎，每个SSL处理器使用独立的引擎
        SSLEngine engine = context.createSSLEngine();
        //根据当前Netty应用是客户端还是服务器进行设置
        engine.setUseClientMode( client );
        //添加到管道最前面，大部分情况下SSL处理器都应该是第一个
        ch.pipeline().addFirst( "ssl", new SslHandler( engine, startTls ) );
    }
}</pre>
<p>SslHandler提供了一些特殊的方法，可以用于修改其行为，或者在SSL/TLS握手完毕后获得通知：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 200px; text-align: center;">方法</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>setHandshakeTimeout()</td>
<td>设置握手超时的秒数，超时后握手的ChannelFuture得到通知，类似还有setHandshakeTimeoutMillis()</td>
</tr>
<tr>
<td>getHandshakeTimeoutMillis()</td>
<td>获取握手超时毫秒数</td>
</tr>
<tr>
<td>setCloseNotifyTimeout()</td>
<td>设置关闭超时时间，超时后连接会关闭，并导致关闭通知失败</td>
</tr>
<tr>
<td>handshakeFuture()</td>
<td>返回一个ChannelFuture，在握手完毕后得到通知</td>
</tr>
<tr>
<td>close()</td>
<td>发送一个close_notify以请求关闭并销毁底层的SslEngine</td>
</tr>
</tbody>
</table>
<div class="blog_h2"><span class="graybg">基于Netty构建HTTP/HTTPS应用</span></div>
<p>关于HTTP协议的基本知识，参考：<a href="/http-study-note">HTTP协议学习笔记</a></p>
<p>Netty内置了若干用于处理HTTP协议的编解码器，可以方便的基于Netty编写HTTP服务器或者客户端。</p>
<p>从逻辑上，HTTP报文可以分为<span style="background-color: #c0c0c0;">头、分为多块传输的报文体、以及标记报文结尾、附加了HTTP头的尾部</span>。HTTP协议的编解码器必须识别这些部分并做出合适的处理。下表是Netty提供的相关编解码器：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;"> 编解码器</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>HttpRequestEncoder</td>
<td>将HttpRequest、HttpContent消息转换为字节</td>
</tr>
<tr>
<td>HttpResponseEncoder</td>
<td>将HttpResponse、HttpContent消息转换为字节 </td>
</tr>
<tr>
<td>HttpRequestDecoder</td>
<td>将字节解码为HttpRequest、HttpContent</td>
</tr>
<tr>
<td>HttpResponseDecoder</td>
<td>将字节解码为HttpResponse、HttpContent</td>
</tr>
</tbody>
</table>
<p>按如下方式修改ChannelPipeline，可以添加对HTTP协议的支持：</p>
<pre class="crayon-plain-tag">public class HttpDecoderEncoderInitializer extends ChannelInitializer&lt;Channel&gt;
{
    //当前应用是作为HTTP客户端还是服务器
    private final boolean client;

    public HttpDecoderEncoderInitializer( boolean client )
    {
        this.client = client;
    }

    @Override
    protected void initChannel( Channel ch ) throws Exception
    {
        ChannelPipeline pipeline = ch.pipeline();
        //下面的添加的处理器亦可改为：HttpClientCodec、HttpServerCodec
        if ( client )
        {
            pipeline.addLast( "decoder", new HttpResponseDecoder() );
            pipeline.addLast( "encoder", new HttpRequestEncoder() );
        }
        else
        {
            pipeline.addLast( "decoder", new HttpRequestDecoder() );
            pipeline.addLast( "encoder", new HttpResponseEncoder() );
        }
    }
}</pre>
<p>在管道中使用了上述编解码器后，你就可以使用各种HttpObject类型的消息了。但是由于HTTP消息可能分散为多个消息，处理它们比较繁琐，Netty提供了聚合工具，可以将HttpObject聚合为完整的FullHttpRequest、FullHttpResponse消息，要使用此聚合器，需要再HTTP编解码器后面添加：</p>
<pre class="crayon-plain-tag">//限制消息的最大长度为512KB，如果超过会导致TooLongFrameException
pipeline.addLast("aggegator", new HttpObjectAggregator(512 * 1024));</pre>
<p> Netty支持开箱即用的HTTP压缩，可以节省网络流量：</p>
<pre class="crayon-plain-tag">if ( client )
{
    pipeline.addLast( "codec", new HttpClientCodec() );
    pipeline.addLast( "decompressor", new HttpContentDecompressor() );
}
else
{
    pipeline.addLast( "codec", new HttpServerCodec() );
    pipeline.addLast( "decompressor", new HttpContentDecompressor() );
}</pre>
<p>如果要启用HTTPS，只需要将SslHandler放到管道的最前面。</p>
<div class="blog_h2"><span class="graybg">处理空闲连接与超时</span></div>
<p>使用TCP长连接，通常需要处理空闲连接与超时。</p>
<p>对于处于空闲状态的TCP连接，为了<span style="background-color: #c0c0c0;">防止对端已经不活动（比如程序崩溃）</span>了而本端却不知道，常常采用“心跳”报文来处理（对于TCP协议来说，使用TCP保活定时器，可以在传输层完成心跳，与应用层心跳各有优劣），如果对端对心跳报文进行响应，说明它还是活动的，否则，则说明连接可能已经无效，需要关闭。</p>
<p>另外一种处理空闲连接的方式是超时，即对端如果空闲过长时间，直接将连接关闭。</p>
<p>Netty提供了若干与空闲连接、超时相关的通道处理器：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;"> 处理器类</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>IdleStateHandler</td>
<td>该处理器在连接空闲过长时间后，触发一个IdleStateEvent事件，可以监听并处理</td>
</tr>
<tr>
<td>ReadTimeoutHandler</td>
<td>在超过一定时间后没有入站消息到达，触发一个ReadTimeoutException异常，并且关闭通道</td>
</tr>
<tr>
<td>WriteTimeoutHandler</td>
<td>在超过一定时间后没有出站消息需要发送，触发一个WriteTimeoutException异常，并且关闭通道</td>
</tr>
</tbody>
</table>
<p>下面是一个心跳处理的示例：</p>
<pre class="crayon-plain-tag">public class IdleStateHandlerInitializer extends ChannelInitializer&lt;Channel&gt;
{

    @Override
    protected void initChannel( Channel ch ) throws Exception
    {
        ChannelPipeline pipeline = ch.pipeline();
        //在空闲60秒后，此处理器被激，触发，调用下一个处理器的userEventTriggered
        //IdleStateHandler构造器的前三个参数：读空闲时间、写空闲时间、都空闲时间
        pipeline.addLast( new IdleStateHandler( 0, 0, 60, TimeUnit.SECONDS ) );
        //在尾部添加心跳处理器
        pipeline.addLast( new HeartbeatHandler() );
    }

    public static final class HeartbeatHandler extends ChannelInboundHandlerAdapter
    {

        private static final ByteBuf HEARTBEAT_SEQUENCE = Unpooled.unreleasableBuffer( Unpooled.copiedBuffer(
                                                                "HEARTBEAT", CharsetUtil.ISO_8859_1 ) );

        @Override
        public void userEventTriggered( ChannelHandlerContext ctx, Object evt ) throws Exception
        {
            if ( evt instanceof IdleStateEvent )
            {
                //发送心跳报文，如果对端不响应，关闭连接
                ctx.writeAndFlush( HEARTBEAT_SEQUENCE.duplicate() ).addListener( ChannelFutureListener.CLOSE_ON_FAILURE );
            }
            else
            {
                super.userEventTriggered( ctx, evt );
            }
        }
    }
}</pre>
<div class="blog_h2"><span class="graybg">解码基于分隔符、定长的协议</span></div>
<p>常见的基于分隔符的协议包括：SMTP、POP3、IMAP、Telnet，很多用户定义协议也是基于分隔符来分割不同的报文的，<span style="background-color: #c0c0c0;">分割后的每一个结果</span>在Netty中被<span style="background-color: #c0c0c0;">称为帧（Frame）</span>。Netty提供以下基于分隔符的解码器：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 200px; text-align: center;">解码器类</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>DelimiterBasedFameDecoder</td>
<td>从输入中使用某种分隔符来分割出帧</td>
</tr>
<tr>
<td>LineBasedFrameDecoder</td>
<td>以<pre class="crayon-plain-tag">\r \n</pre> 作为分隔符来分割出帧</td>
</tr>
</tbody>
</table>
<p>Netty还提供了以下两种定长协议的解码器</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 200px; text-align: center;"> 解码器类</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>FixedLengthFrameDecoder </td>
<td>根据绝对定长方式进行帧分割</td>
</tr>
<tr>
<td>LengthFieldBasedFrameDecoder</td>
<td>根据报文头中的某个指定了报文长度的字段来确定帧长度，进而分割 </td>
</tr>
</tbody>
</table>
<div class="blog_h2"><span class="graybg">写入超长数据</span></div>
<p>对于异步I/O框架来说，如何高效的写入大块数据往往是个挑战。因为当网络饱和（缓冲区已满）后，应当停止继续写入，否则可能导致OutOfMemoryError。</p>
<p>Netty允许基于<span style="background-color: #c0c0c0;">零内存拷贝（zero-memory-copy）</span>方式来处理<span style="background-color: #c0c0c0;">文件内容</span>的写入，它可以让文件系统到网络栈的数据传输全部在内核空间完成并提供最优化的性能。使用零内存拷贝的前提是应用程序不需要对文件的内容进行任何修改（类似于HTTP服务中的静态文件），下面是零内存拷贝的文件传输的代码示例：</p>
<pre class="crayon-plain-tag">FileInputStream in = new FileInputStream( file );
//使用FieRegion可以指定一个文件的范围
FileRegion region = new DefaultFileRegion( in.getChannel(), 0, file.length() );
//零内存拷贝的写入文件
channel.writeAndFlush( region ).addListener( new ChannelFutureListener() {
    public void operationComplete( ChannelFuture future ) throws Exception
    {
        if ( !future.isSuccess() ) ...
    }
} );</pre>
<p>如果要传送的不是文件，而是大块的数据，又如何呢？Netty提供了<span style="background-color: #c0c0c0;">ChunkedWriteHandler</span>这一特殊的处理器，可以用来写入大块的数据，这要这些数据以ChunkedInput实现的形式提供，内置的实现包括：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">ChunkedInput实现 </td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>ChunkedFile</td>
<td>允许写入一个文件（仅当不能使用零内存拷贝时使用）</td>
</tr>
<tr>
<td>ChunkedNioFile</td>
<td>基于NIO，允许写入一个文件（仅当不能使用零内存拷贝时使用）</td>
</tr>
<tr>
<td>ChunkedNioStream</td>
<td>允许传送来自NIO包的ReadableByteChannel的数据流</td>
</tr>
<tr>
<td>ChunkedStream</td>
<td>允许传送来自InputStream的数据流</td>
</tr>
</tbody>
</table>
<p> 下面是使用块传输的代码示例：</p>
<pre class="crayon-plain-tag">public class ChunkedWriteHandlerInitializer extends ChannelInitializer&lt;Channel&gt;
{
    private final File file;
    public ChunkedWriteHandlerInitializer( File file )
    {
        this.file = file;
    }
    @Override
    protected void initChannel( Channel ch ) throws Exception
    {
        ChannelPipeline pipeline = ch.pipeline();
        //该处理器要加在前面，因为它要接受ChunkedInput类型作为输出
        pipeline.addLast( new ChunkedWriteHandler() ); 
        //该处理器用于将输入包装为ChunkedInput
        pipeline.addLast( new WriteStreamHandler() );  
    }
    public final class WriteStreamHandler  extends ChannelInboundHandlerAdapter
    {
        @Override
        public void channelActive( ChannelHandlerContext ctx )  throws Exception
        {
            super.channelActive( ctx );
            //连接建立后，发送一个文件的内容到对端
            ctx.writeAndFlush( new ChunkedStream( new FileInputStream( file ) ) );
        }
    }
}</pre>
<div class="blog_h2"><span class="graybg">串行化数据</span></div>
<p>当需要通过网络传递POJO时，就牵涉到串行化/反串行化的问题。</p>
<div class="blog_h3"><span class="graybg">基于JDK的串行化</span></div>
<p>JDK提供的ObjectOutputStream/ObjectInputStream以及标记接口Serializable来支持串行化。Netty提供了以下编解码器与之对接：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 200px; text-align: center;">编解码器类 </td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>CompatibleObjectDecoder</td>
<td>使用JDK反串行化机制来解码，可以与不使用Netty的对端配合</td>
</tr>
<tr>
<td>CompatibleObjectEncoder</td>
<td>使用JDK串行化机制来编码，可以与不使用Netty的对端配合</td>
</tr>
</tbody>
</table>
<div class="blog_h3"><span class="graybg">基于JBoss Marshalling的串行化</span></div>
<p>JBoss Marshalling是一个第三方串行化框架，比JDK串行化机制快三倍。Netty提供了以下编解码器，可以与JBoss Marshalling对接：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">编解码器类  </td>
<td style="text-align: center;">说明  </td>
</tr>
</thead>
<tbody>
<tr>
<td>MarshallingEncoder</td>
<td>用于串行化处理</td>
</tr>
<tr>
<td>MarshallingDecoder</td>
<td>用于反串行化处理 </td>
</tr>
</tbody>
</table>
<p>下面是一个配合JBoss Marshalling使用的示例：</p>
<pre class="crayon-plain-tag">public class MarshallingInitializer extends ChannelInitializer&lt;Channel&gt;
{

    private final MarshallerProvider   marshallerProvider;

    private final UnmarshallerProvider unmarshallerProvider;

    public MarshallingInitializer( UnmarshallerProvider unmarshallerProvider, MarshallerProvider marshallerProvider )
    {
        this.marshallerProvider = marshallerProvider;
        this.unmarshallerProvider = unmarshallerProvider;
    }

    @Override
    protected void initChannel( Channel channel ) throws Exception
    {
        ChannelPipeline pipeline = channel.pipeline();
        //注册解码、编码器。对端必须也使用JBoss Marshalling
        pipeline.addLast( new MarshallingDecoder( unmarshallerProvider ) );
        pipeline.addLast( new MarshallingEncoder( marshallerProvider ) );
        pipeline.addLast( new ObjectHandler() );
    }

    public static final class ObjectHandler extends SimpleChannelInboundHandler&lt;Serializable&gt;
    {

        @Override
        public void channelRead0( ChannelHandlerContext channelHandlerContext, Serializable serializable ) throws Exception
        {
            //对反串行化后的对象进行处理
        }
    }
}</pre>
<div class="blog_h3"><span class="graybg">基于ProtoBuf的串行化</span></div>
<p>ProtoBuf是由Google开源的、用于方便的编解码结构化数据的框架，该框架具有多种语言的绑定，非常适合跨语言项目的模块之间的通信。Netty提供了以下编解码器实现：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 200px; text-align: center;"> 编解码器类</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>ProtobufDecoder</td>
<td>基于ProtoBuf进行解码</td>
</tr>
<tr>
<td>ProtobufEncoder</td>
<td>基于ProtoBuf进行编码 </td>
</tr>
<tr>
<td>ProtobufVarint32FrameDecoder</td>
<td>基于Varint32进行帧分割</td>
</tr>
</tbody>
</table>
<p>示例代码：</p>
<pre class="crayon-plain-tag">public class ProtoBufInitializer extends ChannelInitializer&lt;Channel&gt;
{

    private final MessageLite lite;

    public ProtoBufInitializer( MessageLite lite )
    {
        this.lite = lite;
    }

    @Override
    protected void initChannel( Channel ch ) throws Exception
    {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast( new ProtobufVarint32FrameDecoder() ); //用于帧分割
        pipeline.addLast( new ProtobufEncoder() ); 
        pipeline.addLast( new ProtobufDecoder( lite ) );
        pipeline.addLast( new ObjectHandler() );
    }

    public static final class ObjectHandler extends SimpleChannelInboundHandler&lt;Object&gt;
    {
        @Override
        public void channelRead0( ChannelHandlerContext ctx, Object msg ) throws Exception
        {
        }
    }
}</pre>
<div class="blog_h1"><span class="graybg">启动Netty应用程序</span></div>
<p>Netty应用程序有两种启动类型：</p>
<ol>
<li>一种作为类似服务器（Server-like）的通道启动，可以<span style="background-color: #c0c0c0;">接受连接</span>，并且为每一个接受的连接<span style="background-color: #c0c0c0;">创建子通道</span></li>
<li>另外一种作为类似于客户端的通道启动，它不会创建子通道，所有操作都在父通道中完成。这类通道不但用于TCP连接的客户端，还用于<span style="background-color: #c0c0c0;">无连接通信的服务器端</span></li>
</ol>
<p>由于很多通道使用相同或者类似的属性，为了简化处理，Netty使AbstractBootstrap类可克隆。克隆时，配置信息将被深拷贝，而底层的<span style="background-color: #c0c0c0;">事件循环组则仅仅会浅拷贝</span>。</p>
<div class="blog_h2"><span class="graybg">启动客户端或无连接协议</span></div>
<p> 需要启动客户端或者无连接协议时，必须使用Bootstrap类，该类提供以下方法</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">方法 </td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>group()</td>
<td>设置用于处理I/O的事件循环组。事件循环组的类型必须与通道类型匹配，不能使用OIO的事件循环组处理NIO通道</td>
</tr>
<tr>
<td>channel()</td>
<td>实例化通道时使用的类</td>
</tr>
<tr>
<td>channelFactory()</td>
<td>如果通道不能基于0-arg构造器创建，可以提供一个工厂类</td>
</tr>
<tr>
<td>localAddress()</td>
<td>通道绑定到的本地地址，如果不指定，将由操作系统随机指定。可以在bind()、connect()时指定本地地址</td>
</tr>
<tr>
<td>option()</td>
<td>需要应用到通道的ChannelConfig的ChannelOptions。这些选项会在bind()、connect()被调用时，设置到通道上。在此之后<span style="background-color: #c0c0c0;">改变这些选项没有意义</span>。支持哪些ChannelOptions取决于具体的通道类型</td>
</tr>
<tr>
<td>attr()</td>
<td>在bind()、connect()时，为目标通道设置属性，在这两个方法之后设置无效</td>
</tr>
<tr>
<td>handler()</td>
<td>设置通道处理器</td>
</tr>
<tr>
<td>clone()</td>
<td>克隆当前Bootstrap对象</td>
</tr>
<tr>
<td>remoteAddress()</td>
<td>设置需要连接的远程地址，可以在connect()时设置</td>
</tr>
<tr>
<td>connect()</td>
<td>尝试连接到对端并返回一个ChannelFuture</td>
</tr>
<tr>
<td>bind()</td>
<td>尝试绑定一个本地地址并返回一个ChannelFuture，在绑定成功后，可能需要通过connect连接到对端</td>
</tr>
</tbody>
</table>
<div class="blog_h2"><span class="graybg">启动服务端</span></div>
<p> 需要启动服务器端时，必须使用ServerBootstrap类，该类提供以下方法：</p>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 150px; text-align: center;">方法</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>group()</td>
<td>指定事件循环组，可以指定两个，一个单纯用于接受连接，另外一个用于处理子通道的I/O</td>
</tr>
<tr>
<td>channel()</td>
<td>用于创建服务器通道（ServerChannel）实例的类</td>
</tr>
<tr>
<td>channelFactory()</td>
<td>创建服务器通道的工厂</td>
</tr>
<tr>
<td>localAddress()</td>
<td>服务器通道绑定的本地地址</td>
</tr>
<tr>
<td>option()</td>
<td>服务器通道的选项</td>
</tr>
<tr>
<td>childOption()</td>
<td>子通道的选项。每当accept一个客户端连接后，服务器通道就会创建一个子通道</td>
</tr>
<tr>
<td>attr()</td>
<td>服务器通道的属性</td>
</tr>
<tr>
<td>childAttr()</td>
<td>子通道的属性</td>
</tr>
<tr>
<td>handler()</td>
<td>服务器通道的处理器，一般不需要指定</td>
</tr>
<tr>
<td>childHandler()</td>
<td>子通道的处理器</td>
</tr>
<tr>
<td>clone()</td>
<td>克隆配置</td>
</tr>
<tr>
<td>bind()</td>
<td>绑定到本地地址并且返回一个ChannelFuture</td>
</tr>
</tbody>
</table>
<div class="blog_h2"><span class="graybg">在通道内部启动一个客户端</span></div>
<p>假设你正在编写一个代理服务器，可能遇到如下的应用场景：</p>
<ol>
<li>代理服务器启动监听</li>
<li>客户端连接到代理服务器，要求访问某个URL</li>
<li>代理服务器访问第三方服务器，访问URL并获取数据</li>
<li>代理服务器将数据返回给客户端</li>
</ol>
<p>在上面的情况下，需要在通道内部启动一个客户端通道：第3、4部通常发生在入站请求事件的处理方法channelRead中，这是你可以创建一个全新的Bootstrap供客户端使用，但是更好的做法是复用代理服务器的事件循环，以减少资源消耗：</p>
<pre class="crayon-plain-tag">@Override
public void channelActive( ChannelHandlerContext ctx ) throws Exception
{
    //一旦客户端连接到此代理服务器
    Bootstrap bootstrap = new Bootstrap();
    //就尝试启动一个客户端，连接gmem.cc获取内容
    bootstrap
            .channel( NioSocketChannel.class )
            .handler(
                    new SimpleChannelInboundHandler&lt;ByteBuf&gt;() {

                        @Override
                        protected void channelRead0( ChannelHandlerContext ctx, ByteBuf in ) throws Exception
                        {
                            //在此读取gmem.cc发来的内容
                        }
                    } );
    //注意：这里我们让客户端直接使用了代理服务器的事件循环组
    bootstrap.group( ctx.channel().eventLoop() );
    bootstrap.connect( new InetSocketAddress( "http://gmem.cc", 80 ) );
}</pre>
<div class="blog_h2"><span class="graybg">使用ChannelOptions和属性（attr）</span></div>
<p>每个通道设置选项是非常繁琐的事情，幸好Netty提供了在Bootstrap时为通道预先设置选项的接口options，该接口允许指定ChannelOptions给未来创建的通道。这些选项可以使用低级别的API，以控制连接的各项特性。</p>
<p>属性（Attributes）则允许你将自定义数据（例如用户身份信息）与通道（线程）安全的进行关联。</p>
<div class="blog_h1"><span class="graybg">通过Netty实现UDP应用</span></div>
<p>UDP是无连接的协议，<span style="background-color: #c0c0c0;">性能要求高（比起TCP，速度相当快）、对丢包较为容忍</span>的应用场景下适合使用UDP。DNS就是一种基于UDP的常见协议。</p>
<div class="blog_h2"><span class="graybg">UDP广播</span></div>
<p>本节将以一个模拟Syslog的广播应用场景，来说明如何通过Netty实现UDP通信：</p>
<ol>
<li>读取日志文件的内容</li>
<li>将每一行广播出去</li>
<li>网络上所有的订阅者监听并获取广播内容</li>
</ol>
<p>广播类（发布者）代码示例：</p>
<pre class="crayon-plain-tag">public class LogEventBroadcaster
{
    public static void main() throws Exception
    {
        //受限的广播地址，发往这类地址的数据报不会被路由器转发出去
        final InetSocketAddress BCAST_ADDR = new InetSocketAddress( "255.255.255.255", Helper.DEFAULT_PORT );
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group( group )
                //使用基于NIO的数据报通道类
                .channel( NioDatagramChannel.class )
                //该选项指明使用广播方式发送数据
                .option( ChannelOption.SO_BROADCAST, true )
                //处理出站的LogEvent类型的数据
                .handler( new MessageToMessageEncoder&lt;LogEvent&gt;() {

                    @Override
                    protected void encode( ChannelHandlerContext ctx, LogEvent event, List&lt;Object&gt; out ) throws Exception
                    {
                        ByteBuf buf = ctx.alloc().buffer();
                        buf.writeBytes( event.getMsg().getBytes( CharsetUtil.UTF_8 ) );
                        //将日志事件封装为数据报，指定目的地址为广播地址
                        //Netty会自动处理此类型的消息，并执行广播
                        out.add( new DatagramPacket( buf, BCAST_ADDR ) );
                    }

                } );
        try
        {
            Channel ch = bootstrap.bind().syncUninterruptibly().channel();
            File file = new File( "syslog" );
            boolean eof = false;
            int line = 0;
            while ( !eof )
            {
                LogEvent event = readLineAsEvent( file, line++ );
                ch.write( event );
            }
        }
        finally
        {
            group.shutdownGracefully();
        }
    }

    private static LogEvent readLineAsEvent( File file, int line )
    {
        //从文件中读取一行
        String content = read( file, line );
        return new LogEvent( content );
    }
}</pre>
<p>监听类（订阅者）代码示例： </p>
<pre class="crayon-plain-tag">public class LogEventMonitor
{
    public static void main( String[] args ) throws InterruptedException
    {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group( group )
                //UDP客户端与服务端的配置一样
                .channel( NioDatagramChannel.class )
                .option( ChannelOption.SO_BROADCAST, true )
                .handler( new ChannelInitializer&lt;Channel&gt;() {
 
                    @Override
                    protected void initChannel( Channel channel ) throws Exception
                    {
                        ChannelPipeline pipeline = channel.pipeline();
                        //将UDP数据报解析为LogEvent
                        pipeline.addLast( new MessageToMessageDecoder&lt;DatagramPacket&gt;() {
 
                            @Override
                            protected void decode( ChannelHandlerContext ctx, DatagramPacket pkt, List&lt;Object&gt; out ) throws Exception
                            {
                                ByteBuf data = pkt.content();
                                out.add( new LogEvent( data.toString( CharsetUtil.UTF_8 ) ) );
                            }
                        } );
                        pipeline.addLast( new SimpleChannelInboundHandler&lt;LogEvent&gt;() {
 
                            @Override
                            protected void channelRead0( ChannelHandlerContext ctx, LogEvent msg ) throws Exception
                            {
                                //处理日志
                            }
                        } );
                    }
                } );
        try
        {
            //绑定UDP端口以监听
            Channel ch = bootstrap.bind( Helper.DEFAULT_PORT ).syncUninterruptibly().channel();
            ch.closeFuture().await();
        }
        finally
        {
            group.shutdownGracefully();
        }
    }
}</pre>
<div class="blog_h2"><span class="graybg">UDP多播（组播）</span></div>
<p>多播与广播类似，下面是一个支持收发多播报文的代码样例：</p>
<pre class="crayon-plain-tag">public class Multicaster
{
 
    private static final Logger LOGGER = LoggerFactory.getLogger( Multicaster.class );
 
    public static void main( String[] args ) throws Exception
    {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup group = new NioEventLoopGroup();
        bootstrap.group( group )
                //基于NIO的多播，必须要求JDK1.7+
                .channelFactory( new ChannelFactory&lt;Channel&gt;() {
 
                    @Override
                    public Channel newChannel()
                    {
                        //强制使用IPv4套接字，否则可能报错：
                        //IPv6 socket cannot join IPv4 multicast group
                        return new NioDatagramChannel( InternetProtocolFamily.IPv4 );
                    }
                } )
                .handler( new ChannelInitializer&lt;Channel&gt;() {
 
                    @Override
                    protected void initChannel( Channel ch ) throws Exception
                    {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast( new ChannelInboundHandlerAdapter() {
 
                            public void channelRead( ChannelHandlerContext ctx, Object msg ) throws Exception
                            {
                                DatagramPacket pkt = (DatagramPacket) msg;
                                LOGGER.debug( "Received message from multicast group: {}", pkt.content().toString( CharsetUtil.UTF_8 ) );
                                ReferenceCountUtil.release( msg );
                            }
                        } );
                        pipeline.addLast( new ChannelOutboundHandlerAdapter() {
 
                            public void write( ChannelHandlerContext ctx, Object msg, ChannelPromise promise ) throws Exception
                            {
                                LOGGER.debug( "Message to be sent to multicast group: {}", msg );
                                super.write( ctx, msg, promise );
                            }
                        } );
 
                    }
                } );
 
        try
        {
            int gport = 6155;
            InetSocketAddress gaddr = new InetSocketAddress( "239.255.2.3", gport );
            //要监听来自多播组的信息，必须绑定到多播端口对应的通配符地址
            NioDatagramChannel ch = (NioDatagramChannel) bootstrap.bind( gport ).syncUninterruptibly().channel();
            //多播地址总是需要跟一个网络接口关联的，这里使用IPv4的环回网卡
            NetworkInterface nif = NetworkInterface.getByInetAddress( NetUtil.LOCALHOST4 );
            //加入多播组，之后，当前套接字才能针对多播组收发消息
            ch.joinGroup( gaddr, nif ).sync();
            //向多播组发送信息
            ByteBuf msg = Unpooled.copiedBuffer( "My bonnie is over the ocean.", CharsetUtil.UTF_8 );
            ch.writeAndFlush( new DatagramPacket( msg, gaddr ) ).sync();
            //离开多播组
            ch.leaveGroup( gaddr, nif ).sync();
            ch.close();
        }
        finally
        {
            group.shutdownGracefully();
        }
    }
} </pre>
</div><p>The post <a rel="nofollow" href="https://blog.gmem.cc/netty-study-note">Netty学习笔记</a> appeared first on <a rel="nofollow" href="https://blog.gmem.cc">绿色记忆</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://blog.gmem.cc/netty-study-note/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>使用Java进行网络编程</title>
		<link>https://blog.gmem.cc/java-network-programming</link>
		<comments>https://blog.gmem.cc/java-network-programming#comments</comments>
		<pubDate>Wed, 11 Apr 2012 01:41:32 +0000</pubDate>
		<dc:creator><![CDATA[Alex]]></dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Network]]></category>
		<category><![CDATA[Netty]]></category>
		<category><![CDATA[NIO]]></category>

		<guid isPermaLink="false">http://blog.gmem.cc/?p=5303</guid>
		<description><![CDATA[<p>Java网络编程的特点 底层细节被隐藏：传统的网络编程依赖操作系统提供的各种函数，使用起来异常复杂，需要关注网络协议的底层细节。而Java平台对网络编程接口进行一致性封装，内置的线程机制也便于操控并发的网络连接 Java网络编程原生接口  类/接口 说明  InetAddress 代表一个IP地址，支持根据主机名、域名获取IP地址，或者执行DNS反查，亦可对地址的性质进行判断 InetSocketAddress 代表一个InetAddress与有一个端口号的组合 ServerSocket 代表服务器端的侦听对象，本身和套接字无关（比较奇怪的命名）。其accept方法一旦侦听到一个客户端连接，即返回代表套接字的Socket对象 Socket 代表连接双方的套接字对象。客户用它初始一次连接，服务器端接受连接后也得到该对象。可以使用getInputStream()、getOutputStream()方法来读写Socket TCP编程 基于原生API编程 传统Socket API的多客户端回响服务 [crayon-69d53f021b675804641296/] 但凡是这种每个Socket对应一个处理线程的服务器端，其scaliblity都非常差。因为线程是较为昂贵的资源，操作系统中线程数量过多时，上下文切换的开销将很大，并且操作系统支持的线程是有限的。 相比起线程，Socket本身是非常廉价的资源，维持一个TCP连接并不需要消耗多少内存或者网络流量。 [crayon-69d53f021b67b481615011/] 基于NIO的多客户端回响服务 <a class="read-more" href="https://blog.gmem.cc/java-network-programming">[...]</a></p>
<p>The post <a rel="nofollow" href="https://blog.gmem.cc/java-network-programming">使用Java进行网络编程</a> appeared first on <a rel="nofollow" href="https://blog.gmem.cc">绿色记忆</a>.</p>
]]></description>
				<content:encoded><![CDATA[<div class="wri_content_clear_both"><div class="blog_h1"><span class="graybg">Java网络编程的特点</span></div>
<ol>
<li>底层细节被隐藏：传统的网络编程依赖操作系统提供的各种函数，使用起来异常复杂，需要关注网络协议的底层细节。而Java平台对网络编程接口进行一致性封装，内置的线程机制也便于操控并发的网络连接</li>
</ol>
<div class="blog_h1"><span class="graybg">Java网络编程原生接口</span></div>
<table style="width: 100%;" border="1" cellspacing="0" cellpadding="5">
<thead>
<tr>
<td style="width: 200px; text-align: center;"> 类/接口</td>
<td style="text-align: center;">说明 </td>
</tr>
</thead>
<tbody>
<tr>
<td>InetAddress</td>
<td>代表一个IP地址，支持根据主机名、域名获取IP地址，或者执行DNS反查，亦可对地址的性质进行判断</td>
</tr>
<tr>
<td>InetSocketAddress</td>
<td>代表一个InetAddress与有一个端口号的组合</td>
</tr>
<tr>
<td>ServerSocket</td>
<td>代表服务器端的侦听对象，本身和套接字无关（比较奇怪的命名）。其accept方法一旦侦听到一个客户端连接，即返回代表套接字的Socket对象</td>
</tr>
<tr>
<td>Socket</td>
<td>代表连接双方的套接字对象。客户用它初始一次连接，服务器端接受连接后也得到该对象。可以使用getInputStream()、getOutputStream()方法来读写Socket</td>
</tr>
</tbody>
</table>
<div class="blog_h1"><span class="graybg">TCP编程</span></div>
<div class="blog_h2"><span class="graybg">基于原生API编程</span></div>
<div class="blog_h3"><span class="graybg">传统Socket API的多客户端回响服务</span></div>
<pre class="crayon-plain-tag">package cc.gmem.study.network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class EchoServer
{


    private static final Logger LOGGER = LoggerFactory.getLogger( EchoServer.class );

    public static class EchoThread extends Thread
    {

        private Socket socket;

        public EchoThread( Socket socket )
        {
            this.socket = socket;
        }

        @Override
        public void run()
        {
            process();
        }

        private void process()
        {
            try
            {
                BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
                //每次println自动刷新缓冲区，使信息能正式通过网络传递出去
                PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) ), true );
                for ( ;; )
                {
                    String request = in.readLine();
                    if ( "bye".equalsIgnoreCase( request ) ) break;
                    out.println( request );
                }
            }
            catch ( IOException e )
            {
                LOGGER.error( e.getMessage(), e );
            }
            finally
            {
                try
                {
                    InetSocketAddress addr = (InetSocketAddress) socket.getRemoteSocketAddress();
                    LOGGER.debug( "{}:{} closing", addr.getHostName(), addr.getPort() );
                    socket.close();
                }
                catch ( IOException e )
                {
                }
            }
        }
    }

    public static void main( String[] args ) throws IOException
    {
        ServerSocket listener = new ServerSocket( Helper.DEFAULT_PORT );
        LOGGER.debug( "Listening on {} ", Helper.DEFAULT_PORT );
        for ( ;; )
        {
            Socket socket = listener.accept();
            InetSocketAddress addr = (InetSocketAddress) socket.getRemoteSocketAddress();
            LOGGER.debug( "{}:{} connected", addr.getHostName(), addr.getPort() );
            EchoThread thread = new EchoThread( socket );
            thread.start();
        }
    }
}</pre>
<p>但凡是这种每个Socket对应一个处理线程的服务器端，其scaliblity都非常差。因为线程是较为昂贵的资源，操作系统中线程数量过多时，上下文切换的开销将很大，并且操作系统支持的线程是有限的。</p>
<p>相比起线程，Socket本身是非常廉价的资源，维持一个TCP连接并不需要消耗多少内存或者网络流量。</p>
<pre class="crayon-plain-tag">package cc.gmem.study.network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class EchoClient
{

    private static final Logger LOGGER = LoggerFactory.getLogger( EchoClient.class );

    public static void main( String[] args ) throws Throwable
    {
        Socket socket = new Socket( InetAddress.getByName( null ), Helper.DEFAULT_PORT );
        try
        {
            BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream() ) );
            PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) ), true );
            for ( int i = 0; i < 10; i++ )
            {
                out.println( "Hello " + i );
                String echo = in.readLine();
                LOGGER.debug( "Message from server: {}", echo );
            }
            out.println( "bye" );
        }
        finally
        {
            InetSocketAddress addr = (InetSocketAddress) socket.getRemoteSocketAddress();
            LOGGER.debug( "Disconnecting from {}:{}", addr.getHostName(), addr.getPort() );
            socket.close();
        }
    }
}</pre>
<div class="blog_h3"><span class="graybg">基于NIO的多客户端回响服务</span></div>
<p>使用Java的NIO编程接口，可以避免一个线程对应一个套接字的处理模式，而让单个线程管理多个套接字，结合使用Selector，可以实现异步IO，大大提升系统的吞吐能力。</p>
<p>代码样例请参考：<a href="/java-nio#socket-programming-with-nio">Java NIO浅析</a></p>
<div class="blog_h3"><span class="graybg">基于NIO2的多客户端回响服务</span></div>
<p>NIO2从JDK1.7开始引入，NIO2允许你<span style="background-color: #c0c0c0;">发起一个IO相关的操作，并提供一个CompletionHandler</span>，该Handler会在前述的I/O操作完毕后自动调用。</p>
<p>NIO2与NIO的最重要区别是，NIO2将<span style="background-color: #c0c0c0;">线程相关</span>的逻辑交由底层代码处理（JDK自己处理事件循环），开发者<span style="background-color: #c0c0c0;">不必检查通道中是否有事件发生（select）</span>。</p>
<pre class="crayon-plain-tag">package cc.gmem.study.network.nio2;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

import cc.gmem.study.network.basic.Helper;


public class NIO2EchoServer
{

    public static void main( String[] args ) throws IOException
    {
        final AsynchronousServerSocketChannel serverChannel = AsynchronousServerSocketChannel.open();
        InetSocketAddress address = new InetSocketAddress( Helper.DEFAULT_PORT );
        serverChannel.bind( address );
        //注册一个“接受”操作。开始接受客户端连接，一旦某个客户端被接受，即调用完成处理器
        serverChannel.accept( null, new CompletionHandler<AsynchronousSocketChannel, Object>() {

            @Override
            public void completed( final AsynchronousSocketChannel channel, Object attachment )
            {
                //继续一个“接受”操作。等待下一个连接的到来
                serverChannel.accept( null, this );
                ByteBuffer buffer = ByteBuffer.allocate( 100 ); //此通道专用的字节缓冲
                //注册一个“读”操作，一旦读取（读取的数据写到buffer中，第一个参数）完毕，即调用完成处理器
                //注意：此处理器是一次性的，读完调用一次，然后即丢弃
                channel.read( buffer, buffer, new EchoCompletionHandler( channel ) );
            }

            @Override
            public void failed( Throwable throwable, Object attachment )
            {
                try
                {
                    //如果出错，关闭套接字
                    serverChannel.close();
                }
                catch ( IOException e )
                {
                }
            }
        } );
    }

    private static final class EchoCompletionHandler implements CompletionHandler<Integer, ByteBuffer>
    {

        private final AsynchronousSocketChannel channel;

        EchoCompletionHandler( AsynchronousSocketChannel channel )
        {
            this.channel = channel;
        }

        /**
         * 该类是读的完成处理器
         * @param buffer 读取到的数据
         */
        @Override
        public void completed( Integer result, ByteBuffer buffer )
        {
            buffer.flip();//切换到读模式
            //注册一个写操作，一旦写入（待写入的数据从buffer中读取）完毕，即调用完成处理器
            channel.write( buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {

                @Override
                public void completed( Integer result, ByteBuffer buffer )
                {
                    if ( buffer.hasRemaining() )
                    {
                        //如果缓冲中仍然有数据，再次注册写操作，继续写
                        channel.write( buffer, buffer, this );
                    }
                    else
                    {
                        buffer.compact();
                        //否则，注册读操作，继续读取
                        channel.read( buffer, buffer, EchoCompletionHandler.this );
                    }
                }

                @Override
                public void failed( Throwable exc, ByteBuffer attachment )
                {
                    try
                    {
                        channel.close();
                    }
                    catch ( IOException e )
                    {
                    }
                }
            } );
        }

        @Override
        public void failed( Throwable exc, ByteBuffer attachment )
        {
            try
            {
                channel.close();
            }
            catch ( IOException e )
            {
            }
        }
    }
}</pre>
<div class="blog_h2"><span class="graybg">基于框架的编程</span></div>
<div id="echo-server-with-netty5" class="blog_h3"><span class="graybg">基于Netty 5.0的回响服务</span></div>
<pre class="crayon-plain-tag">package cc.gmem.study.network.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.ReferenceCountUtil;

import java.nio.charset.Charset;

import cc.gmem.study.network.basic.Helper;

public class NettyEchoServer
{

    //继承一个缺省失配，只覆盖必要的方法
    //注意：该类的实例会为每个通道分别创建一个，因此可以线程安全的使用
    //Netty 4.x的ChannelInboundHandler/ChannelOutboundHandler现在被合并了
    public static class NettyEchoServerHandler extends ChannelHandlerAdapter
    {

        private boolean closeAfterEcho;

        /**
         * 每当从客户端接收到新的数据时，该回调方法被执行
         */
        @Override
        public void channelRead( final ChannelHandlerContext ctx, Object msg )
        {
            try
            {
                //ByteBuf类似于NIO的Buffer，它是一种基于引用计数（reference-counted）的对象
                //应当被明确的释放
                ByteBuf buf = ( (ByteBuf) msg );
                while ( buf.isReadable() )
                {
                    //如果缓冲中还有数据可读，则逐字节的读取并显示
                    System.out.print( (char) buf.readByte() );
                    System.out.flush();
                }
                ChannelFuture cf = ctx.write( msg ); //将接收到的消息逐字的写回去
                ctx.flush(); //flush方法导致刷空写缓冲，导致数据立即通过网络发送到客户端
                if ( closeAfterEcho )
                {
                    //对于任何Future对象，均可以添加监听器回调
                    //回调会在Future对象Done时调用
                    cf.addListener( new ChannelFutureListener() {

                        public void operationComplete( ChannelFuture future )
                        {
                            ctx.close();
                        }
                    } );
                }
            }
            finally
            {
                ReferenceCountUtil.release( msg );
            }
        }

        /**
         * 当发生I/O错误，或者Handler在处理I/O事件时抛出异常，Netty会调用此回调
         */
        @Override
        public void exceptionCaught( ChannelHandlerContext ctx, Throwable cause )
        {
            cause.printStackTrace();
            //一般，通道都应该被关闭；可选的，可能在像客户端发送一个消息后，再关闭
            ctx.close();
        }

    }

    public static void main( String[] args ) throws InterruptedException
    {
        //事件循环组包含若干线程，用来处理I/O事件
        //boss组用来接受（Accept）连接，一旦它接受连接，就将其注册给worker
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //worker组用来处理已经接受的连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try
        {
            //ServerBootstrap是一个NIO服务的辅助启动类
            ServerBootstrap b = new ServerBootstrap();
            b.group( bossGroup, workerGroup )
                    //需要创建的通道类，这里的通道概念与NIO类似，但接口不兼容
                    //NioServerSocketChannel用于接受新的入站连接（SocketChannel）
                    .channel( NioServerSocketChannel.class )
                    //对于所有的被接受的SocketChannel，此childHandler都会对其进行处理
                    //ChannelInitializer是一个特殊的通道处理器（ChannelHandler）
                    //用于协助用户完成对新SocketChannel的配置
                    .childHandler( new ChannelInitializer() {

                        @Override
                        public void initChannel( SocketChannel ch ) throws Exception
                        {
                            //ChannelInitializer的最常见用法：为新的SocketChannel的通道管线（ChannelPipeline）添加ChannelHandler，以实现业务逻辑
                            //如果业务比较复杂，可能在管线中添加多个ChannelHandler
                            //例如，这里添加了三个额外的处理器
                            ChannelPipeline pipeline = ch.pipeline();
                            //基于一个或者多个界定符，来分隔收到的ByteBuf
                            pipeline.addLast( "framer", new DelimiterBasedFrameDecoder( Integer.MAX_VALUE, Delimiters.nulDelimiter() ) );
                            Charset charset = Charset.forName( "UTF-8" );
                            //基于UTF-8进行编解码
                            pipeline.addLast( "decoder", new StringDecoder( charset ) );
                            pipeline.addLast( "encoder", new StringEncoder( charset ) );
                            pipeline.addLast( "handler", new NettyEchoServerHandler() );
                        }
                    } )
                    //在这里，可以指定与特定通道实现相关的参数，例如这里设置了与TCP相关的参数
                    .option( ChannelOption.SO_BACKLOG, 128 )
                    .childOption( ChannelOption.SO_KEEPALIVE, true );

            //绑定到所有网络接口的1918端口
            ChannelFuture f = b.bind( Helper.DEFAULT_PORT ).sync(); //等待Future完成
            f.channel().closeFuture().sync();
        }
        finally
        {
            //关闭线程组被回收资源
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}</pre>
<div id="echo-server-with-netty5" class="blog_h3"><span class="graybg">基于MINA 2.0的回响服务</span></div>
<pre class="crayon-plain-tag">package cc.gmem.study.network.mina;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.util.NoopFilter;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cc.gmem.study.network.basic.Helper;


public class MinaEchoServer
{

    private final static Logger LOGGER = LoggerFactory.getLogger( EchoServer.class );

    public static void main( String[] args ) throws IOException
    {
        SocketAcceptor acceptor = new NioSocketAcceptor();
        acceptor.setReuseAddress( true );
        //处理器包含一系列的回调接口，覆盖连接生命周期的各种事件
        acceptor.setHandler( new IoHandlerAdapter() {

            /**
             * 当连接建立时，I/O处理器线程执行的操作
             */
            @Override
            public void sessionCreated( IoSession session )
            {
                //设置连接空闲时间
                session.getConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
            }

            /**
             * 当连接关闭时执行的操作
             */
            @Override
            public void sessionClosed( IoSession session ) throws Exception
            {
                LOGGER.debug( "Session closed." );
            }

            /**
             * 与sessionCreated之后被执行，不由I/O处理器调用
             */
            @Override
            public void sessionOpened( IoSession session ) throws Exception
            {
                LOGGER.debug( "Session opened." );
            }

            /**
             * 连接空闲后执行操作
             */
            @Override
            public void sessionIdle( IoSession session, IdleStatus status )
            {
                LOGGER.debug( "Session idle: {}", status );
            }

            /**
             * 出现异常时执行的操作
             */
            @Override
            public void exceptionCaught( IoSession session, Throwable cause )
            {
                session.close( true );
            }

            /**
             * 接受到消息时执行的操作
             */
            @Override
            public void messageReceived( IoSession session, Object message ) throws Exception
            {
                LOGGER.info( "Received message : {}", message );
                //缓冲对象
                IoBuffer buf = (IoBuffer) message;
                session.write( buf.duplicate() );
            }
        } );
        DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        //过滤器拦截IoHandler事件，类似于ServletFilter，可以用于完成多种功能，例如身份验证、日志记录、负载控制
        chain.addLast( "filter", new NoopFilter() );
        acceptor.bind( new InetSocketAddress( Helper.DEFAULT_PORT ) );
    }
}</pre>
<p>&nbsp;</p>
</div><p>The post <a rel="nofollow" href="https://blog.gmem.cc/java-network-programming">使用Java进行网络编程</a> appeared first on <a rel="nofollow" href="https://blog.gmem.cc">绿色记忆</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://blog.gmem.cc/java-network-programming/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
