一起学Netty(九)之LengthFieldBasedFrameDecoder

之前介绍了Netty天然的几种解析器,也稍微介绍了一下ByteToMessageDecoder类,我们对Netty的解码器还是有了一定的了解~


今天要介绍的是Netty中一个很重要的解码器,因为相比于其他的普通的解码器,这个解码器用的场景更多,并不是说其他解码器不重要,只是因为我们业务场景所致


在当今比较流行的水平拆分的架构之下,RPC协议很是流行,这样可以使各个项目解耦,使得更加灵活,每个项目之间通过远程调用交互,相互之间定义一个通讯私有协议,然后解析,这样就可以进行数据接口交互


例如我们定义一个这样的协议类:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.codec.lengthFieldBasedFrame;  
  2.   
  3. public class CustomMsg {  
  4.       
  5.     //类型  系统编号 0xAB 表示A系统,0xBC 表示B系统  
  6.     private byte type;  
  7.       
  8.     //信息标志  0xAB 表示心跳包    0xBC 表示超时包  0xCD 业务信息包  
  9.     private byte flag;  
  10.       
  11.     //主题信息的长度  
  12.     private int length;  
  13.       
  14.     //主题信息  
  15.     private String body;  
  16.       
  17.     public CustomMsg() {  
  18.           
  19.     }  
  20.       
  21.     public CustomMsg(byte type, byte flag, int length, String body) {  
  22.         this.type = type;  
  23.         this.flag = flag;  
  24.         this.length = length;  
  25.         this.body = body;  
  26.     }  
  27.   
  28.     public byte getType() {  
  29.         return type;  
  30.     }  
  31.   
  32.     public void setType(byte type) {  
  33.         this.type = type;  
  34.     }  
  35.   
  36.     public byte getFlag() {  
  37.         return flag;  
  38.     }  
  39.   
  40.     public void setFlag(byte flag) {  
  41.         this.flag = flag;  
  42.     }  
  43.   
  44.     public int getLength() {  
  45.         return length;  
  46.     }  
  47.   
  48.     public void setLength(int length) {  
  49.         this.length = length;  
  50.     }  
  51.   
  52.     public String getBody() {  
  53.         return body;  
  54.     }  
  55.   
  56.     public void setBody(String body) {  
  57.         this.body = body;  
  58.     }  
  59.   
  60. }  
我们规定两个系统通过Netty去发送这样的一个格式的信息,CustomMsg中包含这样的几类信息:

1)type表示发送端的系统类型

2)flag表示发送信息的类型,是业务数据,还是心跳包数据

3)length表示主题body的长度

4)body表示主题信息


有了这样的相互规定,发送端与接收端按照这种格式去编码和解码数据,这样就很容易的进行数据交互,当然如果netty不提供任何的类,我们也能进行编码解码,但是Netty还是提供了一个现有的类,这样可以避免我们重复造车,并且即使我们愿意重复造车,我们造的车也不一定比Netty好,所以我们还是直接使用吧


Netty提供的类叫做LengthFieldBasedFrameDecoder,与其他的解码器不一致的地方是它需要几个参数作为它的构造函数参数:


这几个参数的详细解析可以见如下文档:

http://blog.163.com/linfenliang@126/blog/static/127857195201210821145721/


我们也仔细说明一下这些参数,加入我们需要解析,加入我们需要解析我们刚才定义的CustomMsg,我们需要自定义一个decoder,这个类继承Netty提供的LengthFieldBasedFrameDecoder:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.codec.lengthFieldBasedFrame;  
  2.   
  3. import io.netty.buffer.ByteBuf;  
  4. import io.netty.channel.ChannelHandlerContext;  
  5. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;  
  6.   
  7. public class CustomDecoder extends LengthFieldBasedFrameDecoder {  
  8.       
  9.     //判断传送客户端传送过来的数据是否按照协议传输,头部信息的大小应该是 byte+byte+int = 1+1+4 = 6  
  10.     private static final int HEADER_SIZE = 6;  
  11.       
  12.     private byte type;  
  13.       
  14.     private byte flag;  
  15.       
  16.     private int length;  
  17.       
  18.     private String body;  
  19.   
  20.     /** 
  21.      *  
  22.      * @param maxFrameLength 解码时,处理每个帧数据的最大长度 
  23.      * @param lengthFieldOffset 该帧数据中,存放该帧数据的长度的数据的起始位置 
  24.      * @param lengthFieldLength 记录该帧数据长度的字段本身的长度 
  25.      * @param lengthAdjustment 修改帧数据长度字段中定义的值,可以为负数 
  26.      * @param initialBytesToStrip 解析的时候需要跳过的字节数 
  27.      * @param failFast 为true,当frame长度超过maxFrameLength时立即报TooLongFrameException异常,为false,读取完整个帧再报异常 
  28.      */  
  29.     public CustomDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,  
  30.             int lengthAdjustment, int initialBytesToStrip, boolean failFast) {  
  31.         super(maxFrameLength, lengthFieldOffset, lengthFieldLength,  
  32.                 lengthAdjustment, initialBytesToStrip, failFast);  
  33.     }  
  34.       
  35.     @Override  
  36.     protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {  
  37.         if (in == null) {  
  38.             return null;  
  39.         }  
  40.         if (in.readableBytes() < HEADER_SIZE) {  
  41.             throw new Exception("可读信息段比头部信息都小,你在逗我?");  
  42.         }  
  43.           
  44.         //注意在读的过程中,readIndex的指针也在移动  
  45.         type = in.readByte();  
  46.           
  47.         flag = in.readByte();  
  48.           
  49.         length = in.readInt();  
  50.           
  51.         if (in.readableBytes() < length) {  
  52.             throw new Exception("body字段你告诉我长度是"+length+",但是真实情况是没有这么多,你又逗我?");  
  53.         }  
  54.         ByteBuf buf = in.readBytes(length);  
  55.         byte[] req = new byte[buf.readableBytes()];  
  56.         buf.readBytes(req);  
  57.         body = new String(req, "UTF-8");  
  58.           
  59.         CustomMsg customMsg = new CustomMsg(type,flag,length,body);  
  60.         return customMsg;  
  61.     }  
  62.   
  63. }  
头部信息的大小我们这边写的是6,原因在代码里面也解释了,byte是一个字节,int是四个字节,那么头部大小就是6个字节,接下来就是要定义构造函数了,构造函数的入参的解释代码里已经标注了,我们真实的入参是:

稍微解释一下:

1)LENGTH_FIELD_LENGTH指的就是我们这边CustomMsg中length这个属性的大小,我们这边是int型,所以是4

2)LENGTH_FIELD_OFFSET指的就是我们这边length字段的起始位置,因为前面有type和flag两个属性,且这两个属性都是byte,两个就是2字节,所以偏移量是2

3)LENGTH_ADJUSTMENT指的是length这个属性的值,假如我们的body长度是40,有时候,有些人喜欢将length写成44,因为length本身还占有4个字节,这样就需要调整一下,那么就需要-4,我们这边没有这样做,所以写0就可以了


好了,以下给出完整的代码:

CustomServer.Java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.codec.lengthFieldBasedFrame;  
  2.   
  3. import io.netty.bootstrap.ServerBootstrap;  
  4. import io.netty.channel.ChannelFuture;  
  5. import io.netty.channel.ChannelInitializer;  
  6. import io.netty.channel.ChannelOption;  
  7. import io.netty.channel.EventLoopGroup;  
  8. import io.netty.channel.nio.NioEventLoopGroup;  
  9. import io.netty.channel.socket.SocketChannel;  
  10. import io.netty.channel.socket.nio.NioServerSocketChannel;  
  11.   
  12. import java.net.InetSocketAddress;  
  13.   
  14. public class CustomServer {  
  15.       
  16.     private static final int MAX_FRAME_LENGTH = 1024 * 1024;  
  17.     private static final int LENGTH_FIELD_LENGTH = 4;  
  18.     private static final int LENGTH_FIELD_OFFSET = 2;  
  19.     private static final int LENGTH_ADJUSTMENT = 0;  
  20.     private static final int INITIAL_BYTES_TO_STRIP = 0;  
  21.   
  22.     private int port;  
  23.       
  24.     public CustomServer(int port) {  
  25.         this.port = port;  
  26.     }  
  27.       
  28.     public void start(){  
  29.         EventLoopGroup bossGroup = new NioEventLoopGroup(1);  
  30.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  31.         try {  
  32.             ServerBootstrap sbs = new ServerBootstrap().group(bossGroup,workerGroup).channel(NioServerSocketChannel.class).localAddress(new InetSocketAddress(port))  
  33.                     .childHandler(new ChannelInitializer<SocketChannel>() {  
  34.                           
  35.                         protected void initChannel(SocketChannel ch) throws Exception {  
  36.                              ch.pipeline().addLast(new CustomDecoder(MAX_FRAME_LENGTH,LENGTH_FIELD_LENGTH,LENGTH_FIELD_OFFSET,LENGTH_ADJUSTMENT,INITIAL_BYTES_TO_STRIP,false));  
  37.                              ch.pipeline().addLast(new CustomServerHandler());  
  38.                         };  
  39.                           
  40.                     }).option(ChannelOption.SO_BACKLOG, 128)     
  41.                     .childOption(ChannelOption.SO_KEEPALIVE, true);  
  42.              // 绑定端口,开始接收进来的连接  
  43.              ChannelFuture future = sbs.bind(port).sync();    
  44.                
  45.              System.out.println("Server start listen at " + port );  
  46.              future.channel().closeFuture().sync();  
  47.         } catch (Exception e) {  
  48.             bossGroup.shutdownGracefully();  
  49.             workerGroup.shutdownGracefully();  
  50.         }  
  51.     }  
  52.       
  53.     public static void main(String[] args) throws Exception {  
  54.         int port;  
  55.         if (args.length > 0) {  
  56.             port = Integer.parseInt(args[0]);  
  57.         } else {  
  58.             port = 8080;  
  59.         }  
  60.         new CustomServer(port).start();  
  61.     }  
  62. }  
CustomServerHandler.java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.codec.lengthFieldBasedFrame;  
  2.   
  3. import io.netty.channel.ChannelHandlerContext;  
  4. import io.netty.channel.SimpleChannelInboundHandler;  
  5.   
  6. public class CustomServerHandler extends SimpleChannelInboundHandler<Object> {  
  7.   
  8.     @Override  
  9.     protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {  
  10.         if(msg instanceof CustomMsg) {  
  11.             CustomMsg customMsg = (CustomMsg)msg;  
  12.             System.out.println("Client->Server:"+ctx.channel().remoteAddress()+" send "+customMsg.getBody());  
  13.         }  
  14.           
  15.     }  
  16.   
  17. }  
CustomClient.java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.codec.lengthFieldBasedFrame;  
  2.   
  3. import io.netty.bootstrap.Bootstrap;  
  4. import io.netty.channel.ChannelFuture;  
  5. import io.netty.channel.ChannelInitializer;  
  6. import io.netty.channel.ChannelOption;  
  7. import io.netty.channel.EventLoopGroup;  
  8. import io.netty.channel.nio.NioEventLoopGroup;  
  9. import io.netty.channel.socket.SocketChannel;  
  10. import io.netty.channel.socket.nio.NioSocketChannel;  
  11.   
  12. public class CustomClient {  
  13.       
  14.     static final String HOST = System.getProperty("host""127.0.0.1");  
  15.     static final int PORT = Integer.parseInt(System.getProperty("port""8080"));  
  16.     static final int SIZE = Integer.parseInt(System.getProperty("size""256"));  
  17.   
  18.     public static void main(String[] args) throws Exception {  
  19.   
  20.         // Configure the client.  
  21.         EventLoopGroup group = new NioEventLoopGroup();  
  22.         try {  
  23.             Bootstrap b = new Bootstrap();  
  24.             b.group(group)  
  25.              .channel(NioSocketChannel.class)  
  26.              .option(ChannelOption.TCP_NODELAY, true)  
  27.              .handler(new ChannelInitializer<SocketChannel>() {  
  28.                  @Override  
  29.                  public void initChannel(SocketChannel ch) throws Exception {  
  30.                      ch.pipeline().addLast(new CustomEncoder());  
  31.                      ch.pipeline().addLast(new CustomClientHandler());  
  32.                  }  
  33.              });  
  34.   
  35.             ChannelFuture future = b.connect(HOST, PORT).sync();  
  36.             future.channel().writeAndFlush("Hello Netty Server ,I am a common client");  
  37.             future.channel().closeFuture().sync();  
  38.         } finally {  
  39.             group.shutdownGracefully();  
  40.         }  
  41.     }  
  42.   
  43. }  
CustomClientHandler.java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.codec.lengthFieldBasedFrame;  
  2.   
  3. import io.netty.channel.ChannelHandlerContext;  
  4. import io.netty.channel.ChannelInboundHandlerAdapter;  
  5.   
  6. public class CustomClientHandler extends ChannelInboundHandlerAdapter {  
  7.       
  8.     @Override  
  9.     public void channelActive(ChannelHandlerContext ctx) throws Exception {  
  10.         CustomMsg customMsg = new CustomMsg((byte)0xAB, (byte)0xCD"Hello,Netty".length(), "Hello,Netty");  
  11.         ctx.writeAndFlush(customMsg);  
  12.     }  
  13.   
  14. }  
最最重要的就是两个译码器:

CustomDecoder.java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.codec.lengthFieldBasedFrame;  
  2.   
  3. import io.netty.buffer.ByteBuf;  
  4. import io.netty.channel.ChannelHandlerContext;  
  5. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;  
  6.   
  7. public class CustomDecoder extends LengthFieldBasedFrameDecoder {  
  8.       
  9.     //判断传送客户端传送过来的数据是否按照协议传输,头部信息的大小应该是 byte+byte+int = 1+1+4 = 6  
  10.     private static final int HEADER_SIZE = 6;  
  11.       
  12.     private byte type;  
  13.       
  14.     private byte flag;  
  15.       
  16.     private int length;  
  17.       
  18.     private String body;  
  19.   
  20.     /** 
  21.      *  
  22.      * @param maxFrameLength 解码时,处理每个帧数据的最大长度 
  23.      * @param lengthFieldOffset 该帧数据中,存放该帧数据的长度的数据的起始位置 
  24.      * @param lengthFieldLength 记录该帧数据长度的字段本身的长度 
  25.      * @param lengthAdjustment 修改帧数据长度字段中定义的值,可以为负数 
  26.      * @param initialBytesToStrip 解析的时候需要跳过的字节数 
  27.      * @param failFast 为true,当frame长度超过maxFrameLength时立即报TooLongFrameException异常,为false,读取完整个帧再报异常 
  28.      */  
  29.     public CustomDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength,  
  30.             int lengthAdjustment, int initialBytesToStrip, boolean failFast) {  
  31.         super(maxFrameLength, lengthFieldOffset, lengthFieldLength,  
  32.                 lengthAdjustment, initialBytesToStrip, failFast);  
  33.     }  
  34.       
  35.     @Override  
  36.     protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {  
  37.         if (in == null) {  
  38.             return null;  
  39.         }  
  40.         if (in.readableBytes() < HEADER_SIZE) {  
  41.             throw new Exception("可读信息段比头部信息都小,你在逗我?");  
  42.         }  
  43.           
  44.         //注意在读的过程中,readIndex的指针也在移动  
  45.         type = in.readByte();  
  46.           
  47.         flag = in.readByte();  
  48.           
  49.         length = in.readInt();  
  50.           
  51.         if (in.readableBytes() < length) {  
  52.             throw new Exception("body字段你告诉我长度是"+length+",但是真实情况是没有这么多,你又逗我?");  
  53.         }  
  54.         ByteBuf buf = in.readBytes(length);  
  55.         byte[] req = new byte[buf.readableBytes()];  
  56.         buf.readBytes(req);  
  57.         body = new String(req, "UTF-8");  
  58.           
  59.         CustomMsg customMsg = new CustomMsg(type,flag,length,body);  
  60.         return customMsg;  
  61.     }  
  62.   
  63. }  
CustomEncoder.java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.codec.lengthFieldBasedFrame;  
  2.   
  3. import java.nio.charset.Charset;  
  4.   
  5. import io.netty.buffer.ByteBuf;  
  6. import io.netty.channel.ChannelHandlerContext;  
  7. import io.netty.handler.codec.MessageToByteEncoder;  
  8.   
  9. public class CustomEncoder extends MessageToByteEncoder<CustomMsg> {  
  10.   
  11.     @Override  
  12.     protected void encode(ChannelHandlerContext ctx, CustomMsg msg, ByteBuf out) throws Exception {  
  13.         if(null == msg){  
  14.             throw new Exception("msg is null");  
  15.         }  
  16.           
  17.         String body = msg.getBody();  
  18.         byte[] bodyBytes = body.getBytes(Charset.forName("utf-8"));  
  19.         out.writeByte(msg.getType());  
  20.         out.writeByte(msg.getFlag());  
  21.         out.writeInt(bodyBytes.length);  
  22.         out.writeBytes(bodyBytes);  
  23.           
  24.     }  
  25.   
  26. }  
好了,到此为止代码就全部写完了,运行测试一下:

启动服务器端:


运行客户端后,再回到服务器端的控制台:



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值