netty 对 protobuf 协议的解码与包装探究(2)

netty 默认支持protobuf 的封装与解码,若是通讯双方都使用netty则没有什么障碍,但若是客户端是其它语言(C#)则须要本身仿写与netty一致的方式(解码+封装),提早是必须很了解netty是如何进行封装与解码的。这里主要经过读源码主要类ProtobufVarint32FrameDecoder(解码)+ProtobufVarint32LengthFieldPrepender(封装) 来解析其原理与实现。算法

文章来源http://www.cnblogs.com/tankaixiongide

一,支持protobuf 协议的默认实现

//配置服务端NIO线程组  
        EventLoopGroup bossGroup = new NioEventLoopGroup();  
        EventLoopGroup workerGroup = new NioEventLoopGroup();  
        try{  
            ServerBootstrap b = new ServerBootstrap();  
            b.group(bossGroup, workerGroup)  
                .channel(NioServerSocketChannel.class)  
                .option(ChannelOption.SO_BACKLOG, 1024)  
                .handler(new LoggingHandler(LogLevel.INFO))  
                .childHandler(new ChannelInitializer<SocketChannel>() {  
  
                    @Override  
                    protected void initChannel(SocketChannel ch) throws Exception {  
                        ch.pipeline()  
                        .addLast(new ProtobufVarint32FrameDecoder())                          
                        .addLast(new ProtobufDecoder(  
                                SubscribeReqProto.SubscribeReq.getDefaultInstance()))                         
                        .addLast(new ProtobufVarint32LengthFieldPrepender())                          
                        .addLast(new ProtobufEncoder())                       
                        .addLast(new SubReqServerHandler());                          
                    }  
                      
                });  
            //绑定端口,同步等待成功  
            ChannelFuture f = b.bind(port).sync();  
            //等待服务端监听端口关闭  
            f.channel().closeFuture().sync();  
              
        }finally{  
            //退出时释放资源  
            bossGroup.shutdownGracefully();  
            workerGroup.shutdownGracefully();  
        }

 

以上是提供的默认实现。关键在于ProtobufVarint32FrameDecoder,ProtobufVarint32LengthFieldPrepender类。oop

二,ProtobufVarint32LengthFieldPrepender 编码类

An encoder that prepends the the Google Protocol Buffers 128 Varints integer length field.this

* BEFORE DECODE (300 bytes) AFTER DECODE (302 bytes) * +---------------+ +--------+---------------+ * | Protobuf Data |-------------->| Length | Protobuf Data | * | (300 bytes) | | 0xAC02 | (300 bytes) | * +---------------+ +--------+---------------+

从类的说明来看, proto 消息格式如:Length + Protobuf Data (消息头+消息数据) 方式,这里特别须要注意的是头长使用的是varints方式不是int ,消息头描述消息数据体的长度。为了更减小传输量,消息头采用的是varint 格式。编码

什么是varint?spa

文章来源http://www.cnblogs.com/tankaixiongVarint 是一种紧凑的表示数字的方法。它用一个或多个字节来表示一个数字,值越小的数字使用越少的字节数。这能减小用来表示数字的字节数。 Varint 中的每一个 byte 的最高位 bit 有特殊的含义,若是该位为 1,表示后续的 byte 也是该数字的一部分,若是该位为 0,则结束。其余的 7 个 bit 都用来表示数字。所以小于 128 的数字均可以用一个 byte 表示。大于 128 的数字,会用两个字节。线程

更多可参见我上篇文章netty

最大的区别是消息头它不是固定长度(常见是的使用INT 4个字节固定长度),Varint它用一个或多个字节来表示一个数字决定它不是固定长度!code

ProtobufVarint32LengthFieldPrepender 类的主要方法以下:orm

@Override
    protected void encode(
            ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) throws Exception {
        int bodyLen = msg.readableBytes();
        int headerLen = CodedOutputStream.computeRawVarint32Size(bodyLen);
        out.ensureWritable(headerLen + bodyLen);

        CodedOutputStream headerOut =
                CodedOutputStream.newInstance(new ByteBufOutputStream(out), headerLen);
        headerOut.writeRawVarint32(bodyLen);
        headerOut.flush();

        out.writeBytes(msg, msg.readerIndex(), bodyLen);
    }

 

CodedOutputStream 主要是针对与varints相关操做类。 先看是如何写消息头的,获得bodyLen 消息体长度而后调用computeRawVarint32Size()计算须要多少个字节,

public static int computeRawVarint32Size(final int value) {
    if ((value & (0xffffffff <<  7)) == 0) return 1;
    if ((value & (0xffffffff << 14)) == 0) return 2;
    if ((value & (0xffffffff << 21)) == 0) return 3;
    if ((value & (0xffffffff << 28)) == 0) return 4;
    return 5;
  }

 

0xffffffff << 7 二进制表示11111111111111111111111110000000 ,当与value &计算=0则表示value最大只会是000000000000000000000001111111,一个字节足以。

经过&运算得出使用多少个字节就能够表示当前数字。左移7位是与Varint定义相关,第一位须要保留给标识(1表示后续的 byte 也是该数字的一部分,0则结束)。要表示 int 32位 和多加的每一个字节第一个标识位,多出了4位,因此就最大会有5个字节。

获得了varints值,而后如何写入out? 再看关键方法writeRawVarint32()。

public void writeRawVarint32(int value) throws IOException {
    while (true) {
      //0x7F为127
      if ((value & ~0x7F) == 0) {//是否小于127,小于则一个字节就能够表示了
        writeRawByte(value);
        return;
      } else {
        writeRawByte((value & 0x7F) | 0x80);//因不于小127,加一高位标识
        value >>>= 7;//右移7位,再递归
      }
    }
  }
    /** Write a single byte. */
  public void writeRawByte(final byte value) throws IOException {
    if (position == limit) {
      refreshBuffer();
    }

    buffer[position++] = value;
  }
  
  private void refreshBuffer() throws IOException {
    if (output == null) {
      // We're writing to a single buffer.
      throw new OutOfSpaceException();
    }

    // Since we have an output stream, this is our buffer
    // and buffer offset == 0
    output.write(buffer, 0, position);
    position = 0;
  }

 

byte 的取值(-128~127) , 0x7F为127 , 0x80为128

循环取后7位,若是小于127则结束,不小于第一位加标识位1。 由于循环右移因此,实际位置颠倒了,解码时须要倒过来再拼接。

消息头由于是varint32可变字节,因此比较复杂些,消息体简单直接writeBytes便可。

二,ProtobufVarint32FrameDecoder 解码类

一样对应CodedOutputStream有CodedInputStream类,操做解码时的varints。

@Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        in.markReaderIndex();
        final byte[] buf = new byte[5];
        for (int i = 0; i < buf.length; i ++) {
            if (!in.isReadable()) {
                in.resetReaderIndex();
                return;
            }

            buf[i] = in.readByte();
            if (buf[i] >= 0) {
                int length = CodedInputStream.newInstance(buf, 0, i + 1).readRawVarint32();
                if (length < 0) {
                    throw new CorruptedFrameException("negative length: " + length);
                }

                if (in.readableBytes() < length) {
                    in.resetReaderIndex();
                    return;
                } else {
                    out.add(in.readBytes(length));
                    return;
                }
            }
        }

        // Couldn't find the byte whose MSB is off.
        throw new CorruptedFrameException("length wider than 32-bit");
    }

 

前面说明了最大长度为5个字节因此这里声明了5个长度的字节来读取消息头。

buf[i] >= 0 这里为何是>0而后就能够解码了呢?

仍是这句话:varints第一位表示后续的byte是不是该数字的一部分!

若是字节第一位为1则表示后续还有字节是表示消息头,当这个字节的第一位为1则这个字节确定是负数(字节最高位表示正负),大于等于0表示描述消息体长度的数字已经读完了。

而后调用readRawVarint32() 还原成int ,与以前 writeRawVarint32()反其道而行。

public int readRawVarint32() throws IOException {
   byte tmp = readRawByte();
   if (tmp >= 0) {
     return tmp;
   }
   int result = tmp & 0x7f;
   if ((tmp = readRawByte()) >= 0) {
     result |= tmp << 7;
   } else {
     result |= (tmp & 0x7f) << 7;
     if ((tmp = readRawByte()) >= 0) {
       result |= tmp << 14;
     } else {
       result |= (tmp & 0x7f) << 14;
       if ((tmp = readRawByte()) >= 0) {
         result |= tmp << 21;
       } else {
         result |= (tmp & 0x7f) << 21;
         result |= (tmp = readRawByte()) << 28;
         if (tmp < 0) {
           // Discard upper 32 bits.
           for (int i = 0; i < 5; i++) {
             if (readRawByte() >= 0) {
               return result;
             }
           }
           throw InvalidProtocolBufferException.malformedVarint();
         }
       }
     }
   }
   return result;
 }

 

取第N字节左移7*N位或|第一个字节拼接,实现了倒序拼接,最后获得了消息体长度。而后根据获得的消息体长度读取数据,若是消息体长度不够则回滚到markReaderIndex,等待数据。

四,总结

文章来源http://www.cnblogs.com/tankaixiong本文主要详细介绍了netty 对 protobuf 协议的解码与包装。重点在消息头 varint32的 算法表示上进行了说明。了解了varint32在协议中的实现,方便应用在其语言对接。

相关文章
相关标签/搜索