前言 本文参考了码友 Nyima 的学习笔记 https:// nyimac.gitee.io/2021/ 04 /25/ Netty%E5%9 F%BA%E7%A1%80 /
 
一、粘包与半包 1. 服务端代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 @Slf4j public  class  HelloServer   {     void  start ()   {         NioEventLoopGroup boss = new  NioEventLoopGroup(1 );         NioEventLoopGroup worker = new  NioEventLoopGroup();         try  {             ServerBootstrap serverBootstrap = new  ServerBootstrap();             serverBootstrap.channel(NioServerSocketChannel.class);             serverBootstrap.group(boss, worker);             serverBootstrap.childHandler(new  ChannelInitializer<SocketChannel>() {                 @Override                  protected  void  initChannel (SocketChannel ch)   {                     ch.pipeline().addLast(new  LoggingHandler(LogLevel.DEBUG));                     ch.pipeline().addLast(new  ChannelInboundHandlerAdapter() {                         @Override                          public  void  channelActive (ChannelHandlerContext ctx)  throws  Exception  {                                                          log.debug("connected {}" , ctx.channel());                             super .channelActive(ctx);                         }                         @Override                          public  void  channelInactive (ChannelHandlerContext ctx)  throws  Exception  {                                                          log.debug("disconnect {}" , ctx.channel());                             super .channelInactive(ctx);                         }                     });                 }             });             ChannelFuture channelFuture = serverBootstrap.bind(8080 );             log.debug("{} binding..." , channelFuture.channel());             channelFuture.sync();             log.debug("{} bound..." , channelFuture.channel());                          channelFuture.channel().closeFuture().sync();         } catch  (InterruptedException e) {             log.error("server error" , e);         } finally  {             boss.shutdownGracefully();             worker.shutdownGracefully();             log.debug("stopped" );         }     }     public  static  void  main (String[] args)   {         new  HelloServer().start();     } }
 
2. 客户端代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 @Slf4j public  class  HelloClient   {     public  static  void  main (String[] args)   {         NioEventLoopGroup loopGroup = new  NioEventLoopGroup();         try  {             Bootstrap bootstrap = new  Bootstrap();             bootstrap.group(loopGroup);             bootstrap.channel(NioSocketChannel.class);             bootstrap.handler(new  ChannelInitializer<SocketChannel>() {                 @Override                  protected  void  initChannel (SocketChannel ch)  throws  Exception  {                     log.debug("connected..." );                     ch.pipeline().addLast(new  ChannelInboundHandlerAdapter() {                         @Override                          public  void  channelActive (ChannelHandlerContext ctx)  throws  Exception  {                             log.debug("sending..." );                                                          for  (int  i = 0 ; i < 10 ; i++) {                                 ByteBuf buffer = ctx.alloc().buffer();                                 buffer.writeBytes(new  byte []{0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 });                                 ctx.writeAndFlush(buffer);                             }                         }                     });                 }             });             ChannelFuture channelFuture = bootstrap.connect("127.0.0.1" , 8080 ).sync();             channelFuture.channel().closeFuture().sync();         } catch  (InterruptedException e) {             log.error("client error" , e);         } finally  {             loopGroup.shutdownGracefully();         }     } }
 
3. 粘包现象 可见虽然客户端是分别以16字节为单位,通过channel向服务器发送了10次数据,可是服务器端却只接收了一次,接收数据的大小为160B,即客户端发送的数据总大小,这就是粘包现象 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 20 :08:59.269  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0x7c21a326 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :1363 ] READ: 160B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000010 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000020 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000030 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000040 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000050 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000060 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000070 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000080| 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000090| 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| +--------+-------------------------------------------------+----------------+
 
4. 半包现象 首先将客户端-服务器之间的 channel 容量 进行调整,即在服务端中添加代码:
1 2  serverBootstrap.option(ChannelOption.SO_RCVBUF, 10 );
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 5901  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0xc73284f3 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :49679 ] READ: 36B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000010 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| |00000020 | 00  01  02  03                                      |....            | +--------+-------------------------------------------------+----------------+5901  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0xc73284f3 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :49679 ] READ: 40B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  00  01  02  03  |................| |00000010 | 04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  00  01  02  03  |................| |00000020 | 04  05  06  07  08 09 0a 0b                         |........        | +--------+-------------------------------------------------+----------------+5901  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0xc73284f3 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :49679 ] READ: 40B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 0c 0d  0e 0f  00  01  02  03  04  05  06  07  08 09 0a 0b |................| |00000010 | 0c 0d  0e 0f  00  01  02  03  04  05  06  07  08 09 0a 0b |................| |00000020 | 0c 0d  0e 0f  00  01  02  03                          |........        | +--------+-------------------------------------------------+----------------+5901  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0xc73284f3 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :49679 ] READ: 40B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  00  01  02  03  |................| |00000010 | 04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  00  01  02  03  |................| |00000020 | 04  05  06  07  08 09 0a 0b                         |........        | +--------+-------------------------------------------------+----------------+5901  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0xc73284f3 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :49679 ] READ: 4B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 0c 0d  0e 0f                                      |....            | +--------+-------------------------------------------------+----------------+
 
①. 注意 1 2 serverBootstrap.option (ChannelOption.SO_RCVBUF , 10 ) 影响的底层接收缓冲区(即滑动窗口)大小, 仅决定了 netty 读取的最小单位,netty 实际每次读取的一般是它的整数倍
 
5. 现象分析 ①. 粘包 
现象
 
原因
应用层
接收方 ByteBuf 设置太大(Netty 默认 1024) 
 
 
传输层-网络层
滑动窗口:假设发送方 256 bytes 表示一个完整报文,但由于接收方处理不及时且窗口大小足够大(大于256 bytes),这 256 bytes 字节就会缓冲在接收方的滑动窗口中, 当滑动窗口中缓冲了多个报文就会粘包 
Nagle 算法:会造成粘包 
 
 
 
 
 
②. 半包 
现象
 
原因
应用层
 
传输层-网络层
滑动窗口:假设接收方的窗口只剩了 128 bytes,发送方的报文大小是 256 bytes,这时接收方窗口中无法容纳发送方的全部报文,发送方只能先发送前 128 bytes,等待 ack 后才能发送剩余部分,这就造成了半包  
 
 
数据链路层
MSS 限制:当发送的数据超过 MSS 限制后,会将数据切分发送,就会造成半包 
 
 
 
 
 
③. 本质 发生粘包与半包现象的本质是因为 TCP 是流式协议,消息无边界 
6. 解决方案 ①. 短链接 客户端每次向服务器发送数据以后,就与服务器断开连接,此时的消息边界为连接建立到连接断开 。
这时便无需使用滑动窗口等技术来缓冲数据,则不会发生粘包现象。
但如果一次性数据发送过多,接收方无法一次性容纳所有数据,还是会发生半包现象,所以短链接无法解决半包现象 
客户端代码改进 
修改public void channelActive(ChannelHandlerContext ctx)方法
1 2 3 4 5 6 7 8 public  void  channelActive (ChannelHandlerContext ctx)  throws  Exception  {     log.debug("sending..." );     ByteBuf buffer = ctx.alloc().buffer(16 );     buffer.writeBytes(new  byte []{0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 });     ctx.writeAndFlush(buffer);          ctx.channel().close(); }
 
将发送步骤整体封装为send()方法,调用10次send()方法,模拟发送10次数据
1 2 3 4 5 6 public  static  void  main (String[] args)   {          for  (int  i = 0 ; i < 10 ; i++) {         send();     } }
 
运行结果 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 6452  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x3eb6a684 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :65024 ] ACTIVE6468  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x3eb6a684 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :65024 ] READ: 16B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| +--------+-------------------------------------------------+----------------+6468  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x3eb6a684 , L:/127.0 .0 .1 :8080  ! R:/127.0 .0 .1 :65024 ] INACTIVE6483  [nioEventLoopGroup-3 -2 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x7dcc31ff , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :65057 ] ACTIVE6483  [nioEventLoopGroup-3 -2 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x7dcc31ff , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :65057 ] READ: 16B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 00  01  02  03  04  05  06  07  08 09 0a 0b 0c 0d  0e 0f  |................| +--------+-------------------------------------------------+----------------+6483  [nioEventLoopGroup-3 -2 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x7dcc31ff , L:/127.0 .0 .1 :8080  ! R:/127.0 .0 .1 :65057 ] INACTIVE ...
 
客户端先于服务器建立连接,此时控制台打印ACTIVE,之后客户端向服务器发送了16B的数据,发送后断开连接,此时控制台打印INACTIVE,可见未出现粘包现象 
②. 定长解码器 客户端于服务器约定一个最大长度,保证客户端每次发送的数据长度都不会大于该长度 。
若发送数据长度不足则需要补齐 至该长度
服务器接收数据时,将接收到的数据按照约定的最大长度进行拆分 ,即使发送过程中产生了粘包,也可以通过定长解码器将数据正确地进行拆分。
服务端需要用到FixedLengthFrameDecoder对数据进行定长解码 ,具体使用方法如下
1 2  ch.pipeline().addLast(new  FixedLengthFrameDecoder(16 ));
 
客户端代码 
客户端发送数据的代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 @Override public  void  channelActive (ChannelHandlerContext ctx)  throws  Exception  {          final  int  maxLength = 16 ;          char  c = 'a' ;          for  (int  i = 0 ; i < 10 ; i++) {         ByteBuf buffer = ctx.alloc().buffer(maxLength);                  byte [] bytes = new  byte [maxLength];                  for  (int  j = 0 ; j < (int )(Math.random()*(maxLength-1 )); j++) {             bytes[j] = (byte ) c;         }         buffer.writeBytes(bytes);         c++;                  ctx.writeAndFlush(buffer);     } }
 
服务器代码 
使用FixedLengthFrameDecoder对粘包数据进行拆分,该handler需要添加在LoggingHandler之前,保证数据被打印时已被拆分
1 2 3  ch.pipeline().addLast(new  FixedLengthFrameDecoder(16 )); ch.pipeline().addLast(new  LoggingHandler(LogLevel.DEBUG));
 
运行结果 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 8222  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0xbc122d07 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :52954 ] READ: 16B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 61  61  61  61  00  00  00  00  00  00  00  00  00  00  00  00  |aaaa............| +--------+-------------------------------------------------+----------------+8222  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0xbc122d07 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :52954 ] READ: 16B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 62  62  62  00  00  00  00  00  00  00  00  00  00  00  00  00  |bbb.............| +--------+-------------------------------------------------+----------------+8222  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0xbc122d07 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :52954 ] READ: 16B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 63  63  00  00  00  00  00  00  00  00  00  00  00  00  00  00  |cc..............| +--------+-------------------------------------------------+----------------+ ...
 
③. 行解码器 行解码器的是通过分隔符对数据进行拆分 来解决粘包半包问题的
可以通过LineBasedFrameDecoder(int maxLength)来拆分以换行符(\n)为分隔符的数据,也可以通过DelimiterBasedFrameDecoder(int maxFrameLength, ByteBuf... delimiters)来 指定通过什么分隔符来拆分数据(可以传入多个分隔符) 
两种解码器都需要传入数据的最大长度 ,若超出最大长度,会抛出TooLongFrameException异常
以换行符 \n 为分隔符 
客户端代码 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @Override public  void  channelActive (ChannelHandlerContext ctx)  throws  Exception  {          final  int  maxLength = 64 ;          char  c = 'a' ;     for  (int  i = 0 ; i < 10 ; i++) {         ByteBuf buffer = ctx.alloc().buffer(maxLength);                  Random random = new  Random();         StringBuilder sb = new  StringBuilder();         for  (int  j = 0 ; j < (int ) (random.nextInt(maxLength - 2 )); j++) {             sb.append(c);         }                  sb.append("\n" );         buffer.writeBytes(sb.toString().getBytes(StandardCharsets.UTF_8));         c++;                  ctx.writeAndFlush(buffer);     } }
 
服务器代码
1 2 3 4  ch.pipeline().addLast(new  LineBasedFrameDecoder(64 )); ch.pipeline().addLast(new  LoggingHandler(LogLevel.DEBUG));
 
运行结果 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 4184  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x9d6ac701 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :58282 ] READ: 10B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 61  61  61  61  61  61  61  61  61  61                    |aaaaaaaaaa      | +--------+-------------------------------------------------+----------------+4184  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x9d6ac701 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :58282 ] READ: 11B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 62  62  62  62  62  62  62  62  62  62  62                 |bbbbbbbbbbb     | +--------+-------------------------------------------------+----------------+4184  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x9d6ac701 , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :58282 ] READ: 2B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 63  63                                            |cc              | +--------+-------------------------------------------------+----------------+ ...
 
以自定义分隔符 \c 为分隔符 
客户端代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @Override public  void  channelActive (ChannelHandlerContext ctx)  throws  Exception  {          final  int  maxLength = 64 ;          char  c = 'a' ;     for  (int  i = 0 ; i < 10 ; i++) {         ByteBuf buffer = ctx.alloc().buffer(maxLength);                  Random random = new  Random();         StringBuilder sb = new  StringBuilder();         for  (int  j = 0 ; j < (int ) (random.nextInt(maxLength - 2 )); j++) {             sb.append(c);c         }                  sb.append("\\c" );         buffer.writeBytes(sb.toString().getBytes(StandardCharsets.UTF_8));         c++;                  ctx.writeAndFlush(buffer);     } }
 
服务器代码
1 2 3 4 5  ByteBuf bufSet = ch.alloc().buffer().writeBytes("\\c" .getBytes(StandardCharsets.UTF_8)); ch.pipeline().addLast(new  DelimiterBasedFrameDecoder(64 , ch.alloc().buffer().writeBytes(bufSet))); ch.pipeline().addLast(new  LoggingHandler(LogLevel.DEBUG));
 
运行结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 8246  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x86215ccd , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :65159 ] READ: 14B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 61  61  61  61  61  61  61  61  61  61  61  61  61  61        |aaaaaaaaaaaaaa  | +--------+-------------------------------------------------+----------------+8247  [nioEventLoopGroup-3 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x86215ccd , L:/127.0 .0 .1 :8080  - R:/127.0 .0 .1 :65159 ] READ: 3B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 62  62  62                                         |bbb             | +--------+-------------------------------------------------+----------------+ ...
 
④. 长度字段解码器 在传送数据时可以在数据中添加一个用于表示有用数据长度的字段 ,在解码时读取出这个用于表明长度的字段,同时读取其他相关参数,即可知道最终需要的数据是什么样子的
LengthFieldBasedFrameDecoder解码器可以提供更为丰富的拆分方法,其构造方法有五个参数
1 2 3 4 public  LengthFieldBasedFrameDecoder (     int  maxFrameLength,     int  lengthFieldOffset, int  lengthFieldLength,     int  lengthAdjustment, int  initialBytesToStrip) 
 
参数解析 
maxFrameLength 数据最大长度
表示数据的最大长度(包括附加信息、长度标识等内容) 
 
 
lengthFieldOffset 数据长度标识的起始偏移量 
用于指明数据第几个字节开始是用于标识有用字节长度的,因为前面可能还有其他附加信息 
 
 
lengthFieldLength 数据长度标识所占字节数 (用于指明有用数据的长度)
 
lengthAdjustment 长度表示与有用数据的偏移量 
用于指明数据长度标识和有用数据之间的距离,因为两者之间还可能有附加信息 
 
 
initialBytesToStrip 数据读取起点 
读取起点,不读取  0 ~ initialBytesToStrip 之间的数据 
 
 
 
参数图解 
1 2 3 4 5 6 7 8 9 10 lengthFieldOffset   = 0  lengthFieldLength   = 2  lengthAdjustment    = 0  initialBytesToStrip = 0  (= do  not strip header)   BEFORE DECODE  (14  bytes)          AFTER DECODE  (14  bytes)  +--------+----------------+      +--------+----------------+ | Length | Actual Content |----->| Length | Actual Content | | 0x000C | "HELLO, WORLD" |      | 0x000C | "HELLO, WORLD" | +--------+----------------+      +--------+----------------+ 
 
从0开始即为长度标识,长度标识长度为2个字节
0x000C  即为后面 HELLO, WORLD的长度
 
1 2 3 4 5 6 7 8 9 10 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" | +--------+----------------+      +----------------+ 
 
从0开始即为长度标识,长度标识长度为2个字节,读取时从第二个字节开始读取 (此处即跳过长度标识)
因为跳过了用于表示长度的2个字节 ,所以此处直接读取HELLO, WORLD
 
1 2 3 4 5 6 7 8 9 10 lengthFieldOffset   = 2  (= the length of Header 1 ) lengthFieldLength   = 3  lengthAdjustment    = 0  initialBytesToStrip = 0    BEFORE DECODE  (17  bytes)                       AFTER DECODE  (17  bytes)  +----------+----------+----------------+      +----------+----------+----------------+ | Header 1 |  Length  | Actual Content |----->| Header 1 |  Length  | Actual Content | |  0xCAFE  | 0x00000C | "HELLO, WORLD" |      |  0xCAFE  | 0x00000C | "HELLO, WORLD" | +----------+----------+----------------+      +----------+----------+----------------+ 
 
长度标识前面还有2个字节的其他内容 (0xCAFE),第三个字节开始才是长度标识,长度表示长度为3个字节(0x00000C)
Header1中有附加信息,读取长度标识时需要跳过这些附加信息来获取长度 
 
1 2 3 4 5 6 7 8 9 10 lengthFieldOffset   = 0  lengthFieldLength   = 3  lengthAdjustment    = 2  (= the length of Header 1 ) initialBytesToStrip = 0    BEFORE DECODE  (17  bytes)                       AFTER DECODE  (17  bytes)  +----------+----------+----------------+      +----------+----------+----------------+ |  Length  | Header 1 | Actual Content |----->|  Length  | Header 1 | Actual Content | | 0x00000C |  0xCAFE  | "HELLO, WORLD" |      | 0x00000C |  0xCAFE  | "HELLO, WORLD" | +----------+----------+----------------+      +----------+----------+----------------+ 
 
从0开始即为长度标识,长度标识长度为3个字节,长度标识之后还有2个字节的其他内容 (0xCAFE)
长度标识(0x00000C)表示的是从其后lengthAdjustment(2个字节)开始的数据的长度, 
**即HELLO, WORLD**,不包括0xCAFE
 
1 2 3 4 5 6 7 8 9 10 lengthFieldOffset   = 1  (= the length of HDR1) lengthFieldLength   = 2  lengthAdjustment    = 1  (= the length of HDR2) initialBytesToStrip = 3  (= the length of HDR1 + LEN)   BEFORE DECODE  (16  bytes)                        AFTER DECODE  (13  bytes)  +------+--------+------+----------------+      +------+----------------+ | HDR1 | Length | HDR2 | Actual Content |----->| HDR2 | Actual Content | | 0xCA | 0x000C | 0xFE | "HELLO, WORLD" |      | 0xFE | "HELLO, WORLD" | +------+--------+------+----------------+      +------+----------------+ 
 
长度标识前面有1个字节的其他内容,后面也有1个字节的其他内容,读取时从长度标识之后3个字节处开始读取 ,
即读取 0xFE HELLO, WORLD
使用EmbeddedChannel模拟测试 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public  class  LTCDecoder   {     public  static  void  main (String[] args)   {                           EmbeddedChannel channel = new  EmbeddedChannel(                                  new  LengthFieldBasedFrameDecoder(                         1024 ,                         1 ,                         4 ,                         1 ,                         6 ),                 new  LoggingHandler(LogLevel.DEBUG)         );                  ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();         send(buffer, "Hello" );         channel.writeInbound(buffer);         send(buffer, "World" );         channel.writeInbound(buffer);     }     private  static  void  send (ByteBuf buf, String msg)   {                  int  length = msg.length();         byte [] bytes = msg.getBytes(StandardCharsets.UTF_8);                           buf.writeByte(0xCA );                  buf.writeInt(length);                  buf.writeByte(0xFE );                  buf.writeBytes(bytes);     } }
 
运行结果 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 19 :39 :49.124  [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ: 5B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 48  65  6c 6c 6f                                   |Hello           | +--------+-------------------------------------------------+----------------+19 :39 :49.126  [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ COMPLETE19 :39 :49.126  [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ: 5B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 57  6f  72  6c 64                                   |World           | +--------+-------------------------------------------------+----------------+19 :39 :49.126  [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ COMPLETE
 
二、协议设计与解析 1. 协议的作用 TCP/IP 中消息传输基于流的方式,没有边界
协议的目的就是划定消息的边界,制定通信双方要共同遵守的通信规则 
2. Redis 协议 如果我们要向Redis服务器发送一条set name Nyima的指令,需要遵守如下协议
1 2 3 4 5 6 7 8 9 10 11  *3 \r\n $3 \r\n set\r\n $4 \r\n name\r\n $5 \r\n Nyima\r\n
 
客户端代码如下 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 public  class  RedisClient   {     static  final  Logger log = LoggerFactory.getLogger(StudyServer.class);     public  static  void  main (String[] args)   {         NioEventLoopGroup group =  new  NioEventLoopGroup();         try  {             ChannelFuture channelFuture = new  Bootstrap()                     .group(group)                     .channel(NioSocketChannel.class)                     .handler(new  ChannelInitializer<SocketChannel>() {                         @Override                          protected  void  initChannel (SocketChannel ch)   {                                                          ch.pipeline().addLast(new  LoggingHandler(LogLevel.DEBUG));                             ch.pipeline().addLast(new  ChannelInboundHandlerAdapter() {                                 @Override                                  public  void  channelActive (ChannelHandlerContext ctx)  throws  Exception  {                                                                          final  byte [] LINE = {'\r' ,'\n' };                                                                          ByteBuf buffer = ctx.alloc().buffer();                                                                                                               buffer.writeBytes("*3" .getBytes());                                     buffer.writeBytes(LINE);                                     buffer.writeBytes("$3" .getBytes());                                     buffer.writeBytes(LINE);                                     buffer.writeBytes("set" .getBytes());                                     buffer.writeBytes(LINE);                                     buffer.writeBytes("$4" .getBytes());                                     buffer.writeBytes(LINE);                                     buffer.writeBytes("name" .getBytes());                                     buffer.writeBytes(LINE);                                     buffer.writeBytes("$5" .getBytes());                                     buffer.writeBytes(LINE);                                     buffer.writeBytes("Nyima" .getBytes());                                     buffer.writeBytes(LINE);                                     ctx.writeAndFlush(buffer);                                 }                             });                         }                     })                     .connect(new  InetSocketAddress("localhost" , 6379 ));             channelFuture.sync();                          channelFuture.channel().close().sync();         } catch  (InterruptedException e) {             e.printStackTrace();         } finally  {                          group.shutdownGracefully();         }     } }
 
控制台打印结果 
1 2 3 4 5 6 7 8 1600  [nioEventLoopGroup-2 -1 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x28c994f1 , L:/127.0 .0 .1 :60792  - R:localhost/127.0 .0 .1 :6379 ] WRITE: 34B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 2a 33  0d  0a 24  33  0d  0a 73  65  74  0d  0a 24  34  0d  |*3. .$3. .set..$4. | |00000010 | 0a 6e 61  6d  65  0d  0a 24  35  0d  0a 4e 79  69  6d  61  |.name..$5. .Nyima| |00000020 | 0d  0a                                           |..              | +--------+-------------------------------------------------+----------------+
 
Redis中查询执行结果 
3. Http 协议 HTTP协议在请求行请求头中都有很多的内容,自己实现较为困难,
可以使用HttpServerCodec作为服务器端的解码器与编码器,来处理HTTP请求 
1 2 3 4 public  final  class  HttpServerCodec  extends  CombinedChannelDuplexHandler <HttpRequestDecoder , HttpResponseEncoder >        implements  HttpServerUpgradeHandler .SourceCodec  
 
服务器代码 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 public  class  HttpServer   {     static  final  Logger log = LoggerFactory.getLogger(StudyServer.class);     public  static  void  main (String[] args)   {         NioEventLoopGroup group = new  NioEventLoopGroup();         new  ServerBootstrap()                 .group(group)                 .channel(NioServerSocketChannel.class)                 .childHandler(new  ChannelInitializer<SocketChannel>() {                     @Override                      protected  void  initChannel (SocketChannel ch)   {                         ch.pipeline().addLast(new  LoggingHandler(LogLevel.DEBUG));                                                  ch.pipeline().addLast(new  HttpServerCodec());                                                  ch.pipeline().addLast(new  SimpleChannelInboundHandler<HttpRequest>() {                             @Override                              protected  void  channelRead0 (ChannelHandlerContext ctx, HttpRequest msg)   {                                                                  log.debug(msg.uri());                                                                  DefaultFullHttpResponse response = new  DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);                                                                  byte [] bytes = "<h1>Hello, World!</h1>" .getBytes(StandardCharsets.UTF_8);                                                                  response.headers().setInt(CONTENT_LENGTH, bytes.length);                                                                  response.content().writeBytes(bytes);                                                                  ctx.writeAndFlush(response);                             }                         });                     }                 })                 .bind(8080 );     } }
 
服务器负责处理请求并响应浏览器。所以只需要处理HTTP请求 即可
1 2  ch.pipeline().addLast(new  SimpleChannelInboundHandler<HttpRequest>()
 
获得请求后,需要返回响应给浏览器。需要创建响应对象DefaultFullHttpResponse,设置HTTP版本号及状态码,为避免浏览器获得响应后,因为获得CONTENT_LENGTH而一直空转,需要添加CONTENT_LENGTH字段,表明响应体中数据的具体长度
1 2 3 4 5 6 7 8  DefaultFullHttpResponse response = new  DefaultFullHttpResponse(msg.protocolVersion(), HttpResponseStatus.OK);byte [] bytes = "<h1>Hello, World!</h1>" .getBytes(StandardCharsets.UTF_8); response.headers().setInt(CONTENT_LENGTH, bytes.length); response.content().writeBytes(bytes);
 
运行结果 
浏览器
控制台
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 1714  [nioEventLoopGroup-2 -2 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x72630ef7 , L:/0 :0 :0 :0 :0 :0 :0 :1 :8080  - R:/0 :0 :0 :0 :0 :0 :0 :1 :55503 ] READ: 688B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 47  45  54  20  2f  66  61  76  69  63  6f  6e 2e 69  63  6f  |GET /favicon.ico| |00000010 | 20  48  54  54  50  2f  31  2e 31  0d  0a 48  6f  73  74  3a | HTTP/1.1 ..Host:| |00000020 | 20  6c 6f  63  61  6c 68  6f  73  74  3a 38  30  38  30  0d  | localhost:8080. | |00000030 | 0a 43  6f  6e 6e 65  63  74  69  6f  6e 3a 20  6b 65  65  |.Connection: kee| |00000040 | 70  2d  61  6c 69  76  65  0d  0a 50  72  61  67  6d  61  3a |p-alive..Pragma:| ....1716  [nioEventLoopGroup-2 -2 ] DEBUG io.netty.handler.logging.LoggingHandler  - [id: 0x72630ef7 , L:/0 :0 :0 :0 :0 :0 :0 :1 :8080  - R:/0 :0 :0 :0 :0 :0 :0 :1 :55503 ] WRITE: 61B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 48  54  54  50  2f  31  2e 31  20  32  30  30  20  4f  4b 0d  |HTTP/1.1  200  OK.| |00000010 | 0a 43  6f  6e 74  65  6e 74  2d  4c 65  6e 67  74  68  3a |.Content-Length:| |00000020 | 20  32  32  0d  0a 0d  0a 3c 68  31  3e 48  65  6c 6c 6f  | 22. ...<h1>Hello| |00000030 | 2c 20  57  6f  72  6c 64  21  3c 2f  68  31  3e          |, World!</h1>   | +--------+-------------------------------------------------+----------------+
 
4. 自定义协议 ①. 组成要素 
魔数 :用来在第一时间判定接收的数据是否为无效数据包 
版本号 :可以支持协议的升级 
序列化算法:消息正文到底采用哪种序列化反序列化方式
如:json、protobuf、hessian、jdk 
 
 
指令类型 :是登录、注册、单聊、群聊… 跟业务相关 
请求序号 :为了双工通信,提供异步能力
因为发送请求时是异步的,例如客户端同时发送1 2 3 4 
服务端就可能收到不同的顺序,为了解决这一问题,请求中就需要添加一项请求序号 加以区别 
 
 
正文长度  
消息正文  
 
②. 编码器与解码器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 public  class  MessageCodec  extends  ByteToMessageCodec <Message >  {     @Override      public  void  encode (ChannelHandlerContext channelHandlerContext, Message msg, ByteBuf out)  throws  Exception  {                  out.writeBytes(new  byte []{'M' ,'A' ,'S' ,'K' });                  out.writeByte(1 );                  out.writeByte(1 );                  out.writeByte(msg.getMessageType());                  out.writeInt(msg.getSequenceId());                  out.writeByte(0xff );                  ByteArrayOutputStream bos = new  ByteArrayOutputStream();         ObjectOutputStream oos = new  ObjectOutputStream(bos);         oos.writeObject(msg);         byte [] bytes = bos.toByteArray();                  out.writeInt(bytes.length);                  out.writeBytes(bytes);     }     @Override      protected  void  decode (ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out)  throws  Exception  {                  int  magic = in.readInt();                  byte  version = in.readByte();                  byte  seqType = in.readByte();                  byte  messageType = in.readByte();                  int  sequenceId = in.readInt();                  in.readByte();                  int  length = in.readInt();                  byte [] bytes = new  byte [length];         in.readBytes(bytes, 0 , length);         ObjectInputStream ois = new  ObjectInputStream(new  ByteArrayInputStream(bytes));         Message message = (Message) ois.readObject();                  out.add(message);                  System.out.println("===========魔数===========" );         System.out.println(magic);         System.out.println("===========版本号===========" );         System.out.println(version);         System.out.println("===========序列化方法===========" );         System.out.println(seqType);         System.out.println("===========指令类型===========" );         System.out.println(messageType);         System.out.println("===========请求序号===========" );         System.out.println(sequenceId);         System.out.println("===========正文长度===========" );         System.out.println(length);         System.out.println("===========正文===========" );         System.out.println(message);     } }
 
编码器与解码器方法源于父类ByteToMessageCodec ,通过该类可以自定义编码器与解码器,泛型类型为被编码与被解码的类 。此处使用了自定义类Message,代表消息
1 public class  MessageCodec  extends  ByteToMessageCodec<Message>Copy 
 
编码器负责将附加信息与正文信息写入到ByteBuf中 ,其中附加信息总字节数最好为2n,不足需要补齐 。正文内容如果为对象,需要通过序列化 将其放入到ByteBuf中
 
解码器负责将ByteBuf中的信息取出,并放入List中 ,该List用于将信息传递给下一个handler
 
 
测试类 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 @Slf4j public  class  MessageCodecTest   {     public  static  void  main (String[] args)  throws  Exception  {             EmbeddedChannel channel = new  EmbeddedChannel();                          channel.pipeline().addLast(new  LengthFieldBasedFrameDecoder(                     1024 ,                     12 ,                     4 ,                     0 ,                     0 ));             channel.pipeline().addLast(new  LoggingHandler(LogLevel.DEBUG));             channel.pipeline().addLast(new  MessageCodec());             LoginRequestMessage user = new  LoginRequestMessage("Masker" , "123" );                          ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();             new  MessageCodec().encode(null , user, byteBuf);             channel.writeInbound(byteBuf);         } }
 
测试类中用到了LengthFieldBasedFrameDecoder ,避免粘包半包问题 
通过 MessageCodec 的 encode 方法将附加信息与正文写入到 ByteBuf 中,通过 channel 执行入站操作。入站时会调用 decode 方法进行解码  
 
Ⅰ. 模拟半包现象 使用slice方法,将解析得到的 ByteBuf 分割为两部分,再将这两部分入站
注意: 因为writeInbound方法会调用release方法释放空间,所以为了避免前一部分被释放,需要让它的引用计数 + 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 @Slf4j public  class  MessageCodecTest   {     public  static  void  main (String[] args)  throws  Exception  {             EmbeddedChannel channel = new  EmbeddedChannel();                      channel.pipeline().addLast(new  LoggingHandler(LogLevel.DEBUG));         channel.pipeline().addLast(new  LengthFieldBasedFrameDecoder(                     1024 ,                     12 ,                     4 ,                     0 ,                     0 ));             channel.pipeline().addLast(new  MessageCodec());             LoginRequestMessage user = new  LoginRequestMessage("Masker" , "123" );                          ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer();             new  MessageCodec().encode(null , user, byteBuf);             ByteBuf byteBuf1 = byteBuf.slice(0 , 100 );             ByteBuf byteBuf2 = byteBuf.slice(100 ,  byteBuf.readableBytes() - 100 );             byteBuf1.retain();              channel.writeInbound(byteBuf1);              channel.writeInbound(byteBuf2);         } }
 
Ⅱ. 测试半包结果 可以从日志看到服务端会分两部分接收 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 17 :39 :25.980  [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ: 100B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 4d  41  53  4b 01  01  00  00  00  00  00  ff 00  00  00  e0 |MASK............| |00000010 | ac ed 00  05  73  72  00  33  63  6f  6d  2e 77  75  2e 73  |....sr.3com.wu.s| |00000020 | 74  75  64  79  2e 6e 65  74  74  79  2e 61  64  76  61  6e |tudy.netty.advan| |00000030 | 63  65  2e 63  68  61  74  2e 4c 6f  67  69  6e 52  65  71  |ce.chat.LoginReq| |00000040 | 75  65  73  74  4d  65  73  73  61  67  65  54  66  c4 03  98  |uestMessageTf...| |00000050 | 1e 3e ee 02  00  02  4c 00  08 70  61  73  73  77  6f  72  |.>....L..passwor| |00000060 | 64  74  00  12                                      |dt..            | +--------+-------------------------------------------------+----------------+17 :39 :25.995  [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ COMPLETE17 :39 :25.996  [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ: 140B          +-------------------------------------------------+          |  0   1   2   3   4   5   6   7   8   9   a  b  c  d  e  f | +--------+-------------------------------------------------+----------------+ |00000000 | 4c 6a 61  76  61  2f  6c 61  6e 67  2f  53  74  72  69  6e |Ljava/lang/Strin| |00000010 | 67  3b 4c 00  08 75  73  65  72  6e 61  6d  65  71  00  7e |g;L..usernameq.~| |00000020 | 00  01  78  72  00  27  63  6f  6d  2e 77  75  2e 73  74  75  |..xr.'com.wu.stu| |00000030| 64 79 2e 6e 65 74 74 79 2e 61 64 76 61 6e 63 65 |dy.netty.advance| |00000040| 2e 63 68 61 74 2e 4d 65 73 73 61 67 65 1a 16 ed |.chat.Message...| |00000050| 6c d5 8e 4f 57 02 00 02 49 00 0b 6d 65 73 73 61 |l..OW...I..messa| |00000060| 67 65 54 79 70 65 49 00 0a 73 65 71 75 65 6e 63 |geTypeI..sequenc| |00000070| 65 49 64 78 70 00 00 00 00 00 00 00 00 74 00 03 |eIdxp........t..| |00000080| 31 32 33 74 00 06 4d 61 73 6b 65 72             |123t..Masker    | +--------+-------------------------------------------------+----------------+ ===========魔数=========== 1296126795 ===========版本号=========== 1 ===========序列化方法=========== 1 ===========指令类型=========== 0 ===========请求序号=========== 0 ===========正文长度=========== 224 ===========正文=========== LoginRequestMessage(super=Message(sequenceId=0, messageType=0), username=Masker, password=123) 17:39:26.118 [main] DEBUG io.netty.handler.logging.LoggingHandler - [id: 0xembedded, L:embedded - R:embedded] READ COMPLETE 
 
Ⅲ. 粘包 因为使用了长度字段解码器  LengthFieldBasedFrameDecoder在解码时读取出这个用于表明长度的字段,所以不会发生粘包现象
③. @Sharable注解 为了提高handler的复用率,可以将handler创建为handler对象 ,然后在不同的channel中使用该handler对象进行处理操作
1 2 3 4 LoggingHandler loggingHandler = new  LoggingHandler(LogLevel.DEBUG); channel1.pipeline().addLast(loggingHandler); channel2.pipeline().addLast(loggingHandler);
 
但是并不是所有的handler都能通过这种方法来提高复用率的 ,例如LengthFieldBasedFrameDecoder。如果多个channel中使用同一个LengthFieldBasedFrameDecoder对象,则可能发生如下问题
channel1中收到了一个半包,LengthFieldBasedFrameDecoder发现不是一条完整的数据,则没有继续向下传播 
此时channel2中也收到了一个半包,因为两个channel使用了同一个LengthFieldBasedFrameDecoder,存入其中的数据刚好拼凑成了一个完整的数据包 。LengthFieldBasedFrameDecoder让该数据包继续向下传播,最终引发错误  
 
为了提高handler的复用率,同时又避免出现一些并发问题,Netty中原生的handler中用@Sharable注解来标明,该handler能否在多个channel中共享。 
只有带有该注解,才能通过对象的方式被共享 ,否则无法被共享
④. 自定义编解码器能否使用@Sharable注解 这需要根据自定义的handler的处理逻辑进行分析 
我们的MessageCodec本身接收的是LengthFieldBasedFrameDecoder处理之后的数据,那么数据肯定是完整的 ,按分析来说是可以添加@Sharable注解的
但是实际情况我们并不能 添加该注解,会抛出异常信息
1 ChannelHandler com.wu.study.netty.advance.protocol.div.MessageCodec is not allowed to be shared
 
如果想要共享,需要怎么办呢? 
继承MessageToMessageDecoder即可。 该类的目标是:将已经被处理的完整数据再次被处理。 
传过来的Message如果是被处理过的完整数据 ,那么被共享也就不会出现问题了,也就可以使用@Sharable注解了。
实现方式与ByteToMessageCodec类似
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 @Slf4j @ChannelHandler .Sharablepublic  class  SharableMessageCodec  extends  MessageToMessageCodec <ByteBuf , Message >  {     @Override      protected  void  encode (ChannelHandlerContext channelHandlerContext, Message msg, List<Object> outList)  throws  Exception  {         ByteBuf out = channelHandlerContext.alloc().buffer();                  out.writeBytes(new  byte []{'M' ,'A' ,'S' ,'K' });                  out.writeByte(1 );                  out.writeByte(1 );                  out.writeByte(msg.getMessageType());                  out.writeInt(msg.getSequenceId());                  out.writeByte(0xff );                  ByteArrayOutputStream bos = new  ByteArrayOutputStream();         ObjectOutputStream oos = new  ObjectOutputStream(bos);         oos.writeObject(msg);         byte [] bytes = bos.toByteArray();                  out.writeInt(bytes.length);                  out.writeBytes(bytes);         outList.add(out);     }     @Override      protected  void  decode (ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> outList)  throws  Exception  {                  int  magic = in.readInt();                  byte  version = in.readByte();                  byte  seqType = in.readByte();                  byte  messageType = in.readByte();                  int  sequenceId = in.readInt();                  in.readByte();                  int  length = in.readInt();                  byte [] bytes = new  byte [length];         in.readBytes(bytes, 0 , length);         ObjectInputStream ois = new  ObjectInputStream(new  ByteArrayInputStream(bytes));         Message message = (Message) ois.readObject();                  outList.add(message);                  System.out.println("===========魔数===========" );         System.out.println(magic);         System.out.println("===========版本号===========" );         System.out.println(version);         System.out.println("===========序列化方法===========" );         System.out.println(seqType);         System.out.println("===========指令类型===========" );         System.out.println(messageType);         System.out.println("===========请求序号===========" );         System.out.println(sequenceId);         System.out.println("===========正文长度===========" );         System.out.println(length);         System.out.println("===========正文===========" );         System.out.println(message);     } }