【Netty学习】 ChannelInitializer 学习

ChannelInitializer在Netty中是一个很重要的东西。也是4.x版本中用户接触比较多的一个类

它本身是继承ChannelInboundHandlerAdapter的。实现ChannelInboundHandler类


【推荐1】Netty4 ChannelPipeLine分析  ★★★★☆

【推荐2】java netty之ChannelPipeline  ★★★☆☆

【推荐3】netty源码分析之FrameDecoder(LengthFieldBasedFrameDecoder)  ★★★☆☆

 

 

ChannelPipeline 中的中的事件流程

  • I/O Request
                                                via Channel or
                                            ChannelHandlerContext
                                                          |
      +---------------------------------------------------+---------------+
      |                           ChannelPipeline         |               |
      |                                                  \|/              |
      |    +---------------------+            +-----------+----------+    |
      |    | Inbound Handler  N  |            | Outbound Handler  1  |    |
      |    +----------+----------+            +-----------+----------+    |
      |              /|\                                  |               |
      |               |                                  \|/              |
      |    +----------+----------+            +-----------+----------+    |
      |    | Inbound Handler N-1 |            | Outbound Handler  2  |    |
      |    +----------+----------+            +-----------+----------+    |
      |              /|\                                  .               |
      |               .                                   .               |
      | ChannelHandlerContext.fireIN_EVT() ChannelHandlerContext.OUT_EVT()|
      |        [ method call]                       [method call]         |
      |               .                                   .               |
      |               .                                  \|/              |
      |    +----------+----------+            +-----------+----------+    |
      |    | Inbound Handler  2  |            | Outbound Handler M-1 |    |
      |    +----------+----------+            +-----------+----------+    |
      |              /|\                                  |               |
      |               |                                  \|/              |
      |    +----------+----------+            +-----------+----------+    |
      |    | Inbound Handler  1  |            | Outbound Handler  M  |    |
      |    +----------+----------+            +-----------+----------+    |
      |              /|\                                  |               |
      +---------------+-----------------------------------+---------------+
                      |                                  \|/
      +---------------+-----------------------------------+---------------+
      |               |                                   |               |
      |       [ Socket.read() ]                    [ Socket.write() ]     |
      |                                                                   |
      |  Netty Internal I/O Threads (Transport Implementation)            |
      +-------------------------------------------------------------------+
     
    这个图是joc里面的ChannelPipeline文档里面的一张示意图。图示的内容是。
    当有IO请求
    ChannelInboundHandler 是从上之下搜索,相应的实现。一次执行。
    4.x版本中的Netty。启用了一个新的东西用于初始ChannelPipeline -> ChannelInitializer<Channel>
    ChannelInitializer有一个抽象未实现的方法:initChannel(C ch) 用于开发者自己定义相关的Handler添加到信道中。原理及详细分析请参考上面推荐的两篇文章。可能版本还不是最新的。但是4.x版本之后的一些大致的思路都是没有什么变化。

    下面把自己写的小东西贴出来。

     1 package com.engine.netty.server.initializer;
     2 
     3 import io.netty.channel.ChannelInitializer;
     4 import io.netty.channel.ChannelPipeline;
     5 import io.netty.channel.socket.SocketChannel;
     6 import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
     7 import io.netty.handler.codec.LengthFieldPrepender;
     8 import io.netty.handler.timeout.IdleStateHandler;
     9 
    10 import com.engine.netty.server.handler.IdleStateCheckHandler;
    11 import com.engine.netty.server.handler.codec.DecoderAMF3;
    12 import com.engine.netty.server.handler.codec.EncoderAMF3;
    13 import com.engine.netty.socket.ChatServerHandler;
    14 
    15 /**
    16  * Creates a newly configured {@link ChannelPipeline} for a new channel.
    17  */
    18 public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {
    19 
    20     @Override
    21     public void initChannel(SocketChannel ch) throws Exception {
    22         ChannelPipeline pipeline = ch.pipeline();
    23 
    24         // 编码或者解码    拆包
    25         /*
    26          * 需要和客户端订立 相关通信协议底层规则 - 【消息长度(2 : short表示 2个字节)】【消息内容】
    27          * lengthFieldLength => 是整数 - 占四个字节 所以同时偏移四个字节 => (0, 4, 0, 4)
    28          * 
    29          * */
    30         pipeline.addLast("framer", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2));
    31         pipeline.addLast("prepender", new LengthFieldPrepender(4, false));
    32 
    33         // 空闲状态检查  间隔无消息,断开连接
    34         pipeline.addLast("idleStateCheck", new IdleStateHandler(0, 0, 600));
    35         pipeline.addLast("idleCheckHandler", new IdleStateCheckHandler());
    36 
    37         // AMF3 编码或者解码
    38         pipeline.addLast("decoder", new DecoderAMF3());
    39         pipeline.addLast("encoder", new EncoderAMF3());
    40 
    41         // 序列化对象object编码和解码 【用于Java Object】
    42         //pipeline.addLast("objectEncoder", new ObjectEncoder());
    43         //pipeline.addLast("objectDecoder", new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
    44 
    45         /*// 以UTF-8格式编码和解码 数据 【用于字符串】
    46         pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
    47         pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));*/
    48 
    49         // and then business logic.
    50         pipeline.addLast("handler", new ChatServerHandler());
    51     }
    52 }
    NettyServerInitializer

    发出去AMF3的东西是上一篇记录里面写的之外。其他两种编码和解码都是官网有相对应例子的。编码和解码说白其实就是对字节数据的翻译。在Netty中数据已ByteBuf保存。ByteBuf提供了很多的方法读取相对应的数据。在这里就不详细介绍了。有兴趣的可以去看看官网的示例。或者是API 文档。文档中有一些类。官方都提供了相对应的代码范例。
    【空闲状态检查】是官网API文档中找到的。
    io.netty.handler.timeout 这个包中就是Netty提供的一些关于读超时,写超时,读写超时。空闲时间等的东西。

    LengthFieldBasedFrameDecoder 和 LengthFieldPrepender
    这两个编码解码 相当于是对数据的处理。
    先讲一下
    LengthFieldBasedFrameDecoder :
    直接通过命名大家很明显的可以理解这个类 一个根据帧长度的解码类。到底是怎么样子的呢?其实很简单。

    LengthFieldBasedFrameDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip)
    参数:
    maxFrameLength: the maximum length of the frame. If the length of the frame is greater than this value, TooLongFrameException will be thrown. (最大帧长)
    lengthFieldOffset: the offset of the length field (偏移量)
    lengthFieldLength: the length of the length field
    lengthAdjustment: the compensation value to add to the value of the length field
    initialBytesToStrip: the number of first bytes to strip out from the decoded frame
    它有5个参数 (详细的解释可以参考推荐文章3).
    说简单点就是第一个是字节消息的最大长度。第二个参数是消息长度这个字节的偏移量。第三个参数是描述字节消息长度的那部分的长度。第四个不解释。第五个是跳过首部的字节长度
    我这边写的0202其实意思就是 我的消息长度是有一个short类型来描述的。short类型的数据占2个字节。第二个2是说在返回最终解码的数据的时候跳过这个描述长度的字节数。
    API文档中的:
    2 bytes length field at offset 0, strip header :
    Because we can get the length of the content by calling ByteBuf.readableBytes(), you might want to strip the length field by specifying initialBytesToStrip. In this example, we specified 2, that is same with the length of the length field, to strip the first two bytes.
    lengthFieldOffset = 0
    lengthFieldLength = 2
    lengthAdjustment = 0
    initialBytesToStrip = 2 (= the length of the Length field)

    BEFORE DECODE (14 bytes) AFTER DECODE (12 bytes)
    +--------+----------------+ +----------------+
    | Length | Actual Content |----->| Actual Content |
    | 0x000C | "HELLO, WORLD" | | "HELLO, WORLD" |
    +--------+----------------+ +----------------+ 

    最后的ChatServerHandler是我自己写的逻辑的Handler

     



    貌似就写到这边了。O(∩_∩)O哈哈~
    
    
posted @ 2013-11-04 18:13  Tiny&zzh  阅读(7608)  评论(0编辑  收藏  举报