Java Code Examples for io.netty.buffer.ByteBuf.markReaderIndex()

The following are Jave code examples for showing how to use markReaderIndex() of the io.netty.buffer.ByteBuf class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: redis-cluster-watchdog   File: ClusterMessageDecoder.java   Source Code and License Vote up 6 votes
protected ClusterMessage decode(ByteBuf in) {
    in.markReaderIndex();
    try {
        ClusterMessage hdr = new ClusterMessage();
        hdr.signature = (String) in.readCharSequence(4, UTF_8);
        hdr.length = in.readInt();
        if (in.readableBytes() < hdr.length - 8) {
            in.resetReaderIndex(); return null;
        }
        hdr.version = Version.valueOf(in.readUnsignedShort());
        if (hdr.version == PROTOCOL_V0) decodeMessageV0(hdr, in);
        else if (hdr.version == PROTOCOL_V1) decodeMessageV1(hdr, in);
        else throw new UnsupportedOperationException("version: " + hdr.version);
        return hdr;
    } catch (Exception e) {
        in.resetReaderIndex(); return null;
    }
}
 
Example 2
Project: MooProject   File: Varint32FrameDecoder.java   Source Code and License Vote up 6 votes
protected void decode(ChannelHandlerContext paramChannelHandlerContext, ByteBuf paramByteBuf, List<Object> paramList)
        throws Exception {
    paramByteBuf.markReaderIndex();
    byte[] arrayOfByte = new byte[5];
    for(int i = 0; i < arrayOfByte.length; i++) {
        if(!paramByteBuf.isReadable()) {
            paramByteBuf.resetReaderIndex();
            return;
        }
        arrayOfByte[i] = paramByteBuf.readByte();
        if(arrayOfByte[i] >= 0) {
            int j = CodedInputStream.newInstance(arrayOfByte, 0, i + 1).readRawVarint32();
            if(j < 0) {
                throw new CorruptedFrameException("negative length: " + j);
            }
            if(paramByteBuf.readableBytes() < j) {
                paramByteBuf.resetReaderIndex();
                return;
            }
            paramList.add(paramByteBuf.readBytes(j));
            return;
        }
    }
    throw new CorruptedFrameException("length wider than 32-bit");
}
 
Example 3
Project: JungleTree   File: PlayStateCodecTest.java   Source Code and License Vote up 6 votes
@Test
public void encode() {
    // Given
    PlayStatePacket expected = createDummyPlayStatePacket();

    ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
    buf.markReaderIndex();

    // When
    subject.encode(expected, buf);

    // Then
    PlayStatePacket actual = subject.decode(buf);
    assertThat(actual).isEqualTo(expected);
    Truth.assertThat(actual.getPlayState()).isEqualTo(expected.getPlayState());
}
 
Example 4
Project: elephant   File: NettyDecoder.java   Source Code and License Vote up 6 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
		List<Object> out) throws Exception {
	//获取消息头所标识的消息体字节数组长度
       if (in.readableBytes() < 4) {
           return;
       }
       in.markReaderIndex();
       int dataLength = in.readInt();
       if (dataLength < 0) {
           ctx.close();
       }
       //若当前可以获取到的字节数小于实际长度,则直接返回,直到当前可以获取到的字节数等于实际长度
       if (in.readableBytes() < dataLength) {
           in.resetReaderIndex();
           return;
       }
       //读取完整的消息体字节数组
       byte[] data = new byte[dataLength];
       in.readBytes(data);

       //将字节数组反序列化为java对象(SerializerEngine参考序列化与反序列化章节)
       Object obj = SerializerEngine.deserialize(data, genericClass, serializeType.getCode());
       out.add(obj);
}
 
Example 5
Project: Quavo   File: GamePacketBuilder.java   Source Code and License Vote up 5 votes
/**
 * Puts the bytes from the specified buffer into this packet's buffer, in reverse.
 *
 * @param buffer The source {@link ByteBuf}.
 */
public void putBytesReverse(ByteBuf buffer) {
	byte[] bytes = new byte[buffer.readableBytes()];
	buffer.markReaderIndex();
	try {
		buffer.readBytes(bytes);
	} finally {
		buffer.resetReaderIndex();
	}
	putBytesReverse(bytes);
}
 
Example 6
Project: CloudNet   File: ProtocolLengthDeserializer.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	in.markReaderIndex();
	byte[] lengthBytes = new byte[3];

	for (int i = 0; i < 3; i++)
	{
		if (!in.isReadable())
		{
			in.resetReaderIndex();
			return;
		}
		lengthBytes[i] = in.readByte();
		if (lengthBytes[i] >= 0)
		{
			ByteBuf buffer = Unpooled.wrappedBuffer(lengthBytes);

			try
			{
				int packetLength = readVarInt(buffer);
				if (in.readableBytes() < packetLength)
				{
					in.resetReaderIndex();
					return;
				}

				out.add(in.readBytes(packetLength));
			}
			finally
			{
				buffer.release();
			}

			return;
		}
	}
}
 
Example 7
Project: dremio-oss   File: MessageDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
  if (!ctx.channel().isOpen()) {
    if (in.readableBytes() > 0) {
      logger.info("Channel is closed, discarding remaining {} byte(s) in buffer.", in.readableBytes());
    }
    in.skipBytes(in.readableBytes());
    return;
  }

  in.markReaderIndex();

  /**
   *  a variable-width message length can be up to five bytes in length. read bytes until we have a length.
   */
  final byte[] buf = new byte[5];
  int length = 0;
  for (int i = 0; i < buf.length; i++) {
    if (!in.isReadable()) {
      in.resetReaderIndex();
      return;
    }

    buf[i] = in.readByte();
    if (buf[i] >= 0) {

      length = CodedInputStream.newInstance(buf, 0, i + 1).readRawVarint32();

      if (length < 0) {
        throw new CorruptedFrameException("negative length: " + length);
      }
      if (length == 0) {
        throw new CorruptedFrameException("Received a message of length 0.");
      }

      if (in.readableBytes() < length) {
        in.resetReaderIndex();
        return;
      } else {
        // complete message in buffer.
        break;
      }
    }
  }

  final ByteBuf frame = in.slice(in.readerIndex(), length);
  try {
    final InboundRpcMessage message = decodeMessage(ctx, frame, length);
    if (message != null) {
      out.add(message);
    }
  } finally {
    in.skipBytes(length);
  }
}
 
Example 8
Project: TakinRPC   File: KyroMsgDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    Stopwatch watch = Stopwatch.createStarted();

    //        Input input = new Input(new ByteBufInputStream(in));
    //        Object result = kryo.readClassAndObject(input);
    //        out.add(result);
    //        input.close();
    if (in.readableBytes() < HEAD_LENGTH) { //这个HEAD_LENGTH是我们用于表示头长度的字节数。  由于Encoder中我们传的是一个int类型的值,所以这里HEAD_LENGTH的值为4.
        return;
    }
    in.markReaderIndex(); //我们标记一下当前的readIndex的位置
    int dataLength = in.readInt(); // 读取传送过来的消息的长度。ByteBuf 的readInt()方法会让他的readIndex增加4
    if (dataLength < 0) { // 我们读到的消息体长度为0,这是不应该出现的情况,这里出现这情况,关闭连接。
        ctx.close();
    }

    if (in.readableBytes() < dataLength) { //读到的消息体长度如果小于我们传送过来的消息长度,则resetReaderIndex. 这个配合markReaderIndex使用的。把readIndex重置到mark的地方
        in.resetReaderIndex();
        return;
    }

    byte[] body = new byte[dataLength]; //传输正常
    in.readBytes(body);

    RemotingProtocol o = convertToObject(body); //将byte数据转化为我们需要的对象
    out.add(o);
    if (logger.isDebugEnabled())
        logger.debug("kyro decoder use:" + watch.toString());
}
 
Example 9
Project: elasticsearch_my   File: ByteBufStreamInput.java   Source Code and License Vote up 5 votes
ByteBufStreamInput(ByteBuf buffer, int length) {
    if (length > buffer.readableBytes()) {
        throw new IndexOutOfBoundsException();
    }
    this.buffer = buffer;
    startIndex = buffer.readerIndex();
    endIndex = startIndex + length;
    buffer.markReaderIndex();
}
 
Example 10
Project: message-broker   File: AmqpDecoder.java   Source Code and License Vote up 5 votes
private void parseFrame(ByteBuf buffer, List<Object> out) throws Exception {
    buffer.markReaderIndex();
    if (buffer.readableBytes() > FRAME_SIZE_WITHOUT_PAYLOAD) {
        byte type = buffer.readByte();
        int channel = buffer.readShort();
        long payloadSize = buffer.readInt();

        long estimatedRemainingSize = payloadSize + 1;
        if (buffer.readableBytes() < estimatedRemainingSize) {
            buffer.resetReaderIndex();
            return;
        }

        GeneralFrame frame = null;
        switch (type) {
            case 1: // Method
                short amqpClass = buffer.readShort();
                short amqpMethod = buffer.readShort();
                AmqMethodBodyFactory factory = methodRegistry.getFactory(amqpClass, amqpMethod);

                frame = factory.newInstance(buffer, channel, payloadSize);
                break;
            case 2: // Header
                frame = HeaderFrame.parse(buffer, channel);
                break;
            case 3: // Body
                frame = ContentFrame.parse(buffer, channel, payloadSize);
                break;
            case 4: // Heartbeat
                throw new Exception("Method Not implemented");
        }

        byte frameEnd = buffer.readByte();
        if (frameEnd != (byte) GeneralFrame.FRAME_END) {
            throw new Exception("Invalid AMQP frame");
        }

        out.add(frame);
    }
}
 
Example 11
Project: CodeBroker   File: ByteArrayPacketCodecDecoder.java   Source Code and License Vote up 5 votes
@Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
//        System.out.println(in.order() + "in.readableBytes()" + in.readableBytes());
//        byte[] bs = new byte[in.readableBytes()];
//        in.readBytes(bs);
//        String fullHexDump = ByteUtils.fullHexDump(bs);
//        System.out.println(fullHexDump);
//        System.out.println(new String(bs));
//        in.resetReaderIndex();
//        in.markReaderIndex();
//		byte[] bs=new byte[in.capacity()];
//		in.readBytes(bs);
////		System.out.println(in.readIntLE());
//		ByteUtils.fullHexDump(bs);
//		in.resetReaderIndex();
        int dataLength = in.readInt();
//        System.out.println(dataLength + "======");
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }

        int opcode = in.readInt();
//        System.out.println("opcode=" + opcode);
        byte[] decoded = new byte[dataLength - 4];
        in.readBytes(decoded);

        BaseByteArrayPacket messagePack = new BaseByteArrayPacket(opcode, decoded);

        out.add(messagePack);

    }
 
Example 12
Project: DNCF   File: CommonDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list)
        throws Exception {
    if (byteBuf.readableBytes() < BASE_LENGTH) {
        logger.error("[error] >>> head length error");
        return;
    }

    byteBuf.markReaderIndex();

    CommonProtocol protocol = new CommonProtocol();
    protocol.setMagic(byteBuf.readShort());
    protocol.setVersion(byteBuf.readShort());
    protocol.setType(byteBuf.readShort());


    if(protocol.getType() != 1) {
        //read len error
        if (byteBuf.readableBytes() < 4) {
            byteBuf.resetReaderIndex();
            return;
        }
        protocol.setLen(byteBuf.readInt());

        //read body error
        if (byteBuf.readableBytes() < protocol.getLen()) {
            byteBuf.resetReaderIndex();
            return;
        }

        byte[] data = new byte[protocol.getLen()];


        byteBuf.readBytes(data);
        protocol.setBody(data);
    }
    list.add(protocol);
}
 
Example 13
Project: lionrpc   File: MessageDecoder.java   Source Code and License Vote up 5 votes
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {

        if(in.readableBytes() < 4){
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if(in.readableBytes() < dataLength){
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);
        
        Kryo kryo = null;
        try{
	        kryo = pool.borrow();
	        Input input = new Input(data);
	        Object obj = kryo.readObject(input,this.clazz);
	        out.add(obj);
        }catch(Exception e){
        	LOG.warn("MessageDecoder happen exception.",e);
        }finally{
        	if(kryo != null){
        		pool.release(kryo);
        	}
        }
    }
 
Example 14
Project: Backmemed   File: NettyVarint21FrameDecoder.java   Source Code and License Vote up 4 votes
protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List<Object> p_decode_3_) throws Exception
{
    p_decode_2_.markReaderIndex();
    byte[] abyte = new byte[3];

    for (int i = 0; i < abyte.length; ++i)
    {
        if (!p_decode_2_.isReadable())
        {
            p_decode_2_.resetReaderIndex();
            return;
        }

        abyte[i] = p_decode_2_.readByte();

        if (abyte[i] >= 0)
        {
            PacketBuffer packetbuffer = new PacketBuffer(Unpooled.wrappedBuffer(abyte));

            try
            {
                int j = packetbuffer.readVarIntFromBuffer();

                if (p_decode_2_.readableBytes() >= j)
                {
                    p_decode_3_.add(p_decode_2_.readBytes(j));
                    return;
                }

                p_decode_2_.resetReaderIndex();
            }
            finally
            {
                packetbuffer.release();
            }

            return;
        }
    }

    throw new CorruptedFrameException("length wider than 21-bit");
}
 
Example 15
Project: CustomWorldGen   File: LegacyPingHandler.java   Source Code and License Vote up 4 votes
public void channelRead(ChannelHandlerContext p_channelRead_1_, Object p_channelRead_2_) throws Exception
{
    ByteBuf bytebuf = (ByteBuf)p_channelRead_2_;
    bytebuf.markReaderIndex();
    boolean flag = true;

    try
    {
        if (bytebuf.readUnsignedByte() == 254)
        {
            InetSocketAddress inetsocketaddress = (InetSocketAddress)p_channelRead_1_.channel().remoteAddress();
            MinecraftServer minecraftserver = this.networkSystem.getServer();
            int i = bytebuf.readableBytes();

            switch (i)
            {
                case 0:
                    LOGGER.debug("Ping: (<1.3.x) from {}:{}", new Object[] {inetsocketaddress.getAddress(), Integer.valueOf(inetsocketaddress.getPort())});
                    String s2 = String.format("%s\u00a7%d\u00a7%d", new Object[] {minecraftserver.getMOTD(), Integer.valueOf(minecraftserver.getCurrentPlayerCount()), Integer.valueOf(minecraftserver.getMaxPlayers())});
                    this.writeAndFlush(p_channelRead_1_, this.getStringBuffer(s2));
                    break;
                case 1:

                    if (bytebuf.readUnsignedByte() != 1)
                    {
                        return;
                    }

                    LOGGER.debug("Ping: (1.4-1.5.x) from {}:{}", new Object[] {inetsocketaddress.getAddress(), Integer.valueOf(inetsocketaddress.getPort())});
                    String s = String.format("\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", new Object[] {Integer.valueOf(127), minecraftserver.getMinecraftVersion(), minecraftserver.getMOTD(), Integer.valueOf(minecraftserver.getCurrentPlayerCount()), Integer.valueOf(minecraftserver.getMaxPlayers())});
                    this.writeAndFlush(p_channelRead_1_, this.getStringBuffer(s));
                    break;
                default:
                    boolean flag1 = bytebuf.readUnsignedByte() == 1;
                    flag1 = flag1 & bytebuf.readUnsignedByte() == 250;
                    flag1 = flag1 & "MC|PingHost".equals(new String(bytebuf.readBytes(bytebuf.readShort() * 2).array(), Charsets.UTF_16BE));
                    int j = bytebuf.readUnsignedShort();
                    flag1 = flag1 & bytebuf.readUnsignedByte() >= 73;
                    flag1 = flag1 & 3 + bytebuf.readBytes(bytebuf.readShort() * 2).array().length + 4 == j;
                    flag1 = flag1 & bytebuf.readInt() <= 65535;
                    flag1 = flag1 & bytebuf.readableBytes() == 0;

                    if (!flag1)
                    {
                        return;
                    }

                    LOGGER.debug("Ping: (1.6) from {}:{}", new Object[] {inetsocketaddress.getAddress(), Integer.valueOf(inetsocketaddress.getPort())});
                    String s1 = String.format("\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", new Object[] {Integer.valueOf(127), minecraftserver.getMinecraftVersion(), minecraftserver.getMOTD(), Integer.valueOf(minecraftserver.getCurrentPlayerCount()), Integer.valueOf(minecraftserver.getMaxPlayers())});
                    ByteBuf bytebuf1 = this.getStringBuffer(s1);

                    try
                    {
                        this.writeAndFlush(p_channelRead_1_, bytebuf1);
                    }
                    finally
                    {
                        bytebuf1.release();
                    }
            }

            bytebuf.release();
            flag = false;
            return;
        }
    }
    catch (RuntimeException var21)
    {
        return;
    }
    finally
    {
        if (flag)
        {
            bytebuf.resetReaderIndex();
            p_channelRead_1_.channel().pipeline().remove("legacy_query");
            p_channelRead_1_.fireChannelRead(p_channelRead_2_);
        }
    }
}
 
Example 16
Project: BaseClient   File: MessageDeserializer2.java   Source Code and License Vote up 4 votes
protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List<Object> p_decode_3_) throws Exception
{
    p_decode_2_.markReaderIndex();
    byte[] abyte = new byte[3];

    for (int i = 0; i < abyte.length; ++i)
    {
        if (!p_decode_2_.isReadable())
        {
            p_decode_2_.resetReaderIndex();
            return;
        }

        abyte[i] = p_decode_2_.readByte();

        if (abyte[i] >= 0)
        {
            PacketBuffer packetbuffer = new PacketBuffer(Unpooled.wrappedBuffer(abyte));

            try
            {
                int j = packetbuffer.readVarIntFromBuffer();

                if (p_decode_2_.readableBytes() >= j)
                {
                    p_decode_3_.add(p_decode_2_.readBytes(j));
                    return;
                }

                p_decode_2_.resetReaderIndex();
            }
            finally
            {
                packetbuffer.release();
            }

            return;
        }
    }

    throw new CorruptedFrameException("length wider than 21-bit");
}
 
Example 17
Project: BaseClient   File: PingResponseHandler.java   Source Code and License Vote up 4 votes
public void channelRead(ChannelHandlerContext p_channelRead_1_, Object p_channelRead_2_) throws Exception
{
    ByteBuf bytebuf = (ByteBuf)p_channelRead_2_;
    bytebuf.markReaderIndex();
    boolean flag = true;

    try
    {
        if (bytebuf.readUnsignedByte() == 254)
        {
            InetSocketAddress inetsocketaddress = (InetSocketAddress)p_channelRead_1_.channel().remoteAddress();
            MinecraftServer minecraftserver = this.networkSystem.getServer();
            int i = bytebuf.readableBytes();

            switch (i)
            {
                case 0:
                    logger.debug("Ping: (<1.3.x) from {}:{}", new Object[] {inetsocketaddress.getAddress(), Integer.valueOf(inetsocketaddress.getPort())});
                    String s2 = String.format("%s\u00a7%d\u00a7%d", new Object[] {minecraftserver.getMOTD(), Integer.valueOf(minecraftserver.getCurrentPlayerCount()), Integer.valueOf(minecraftserver.getMaxPlayers())});
                    this.writeAndFlush(p_channelRead_1_, this.getStringBuffer(s2));
                    break;

                case 1:
                    if (bytebuf.readUnsignedByte() != 1)
                    {
                        return;
                    }

                    logger.debug("Ping: (1.4-1.5.x) from {}:{}", new Object[] {inetsocketaddress.getAddress(), Integer.valueOf(inetsocketaddress.getPort())});
                    String s = String.format("\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", new Object[] {Integer.valueOf(127), minecraftserver.getMinecraftVersion(), minecraftserver.getMOTD(), Integer.valueOf(minecraftserver.getCurrentPlayerCount()), Integer.valueOf(minecraftserver.getMaxPlayers())});
                    this.writeAndFlush(p_channelRead_1_, this.getStringBuffer(s));
                    break;

                default:
                    boolean flag1 = bytebuf.readUnsignedByte() == 1;
                    flag1 = flag1 & bytebuf.readUnsignedByte() == 250;
                    flag1 = flag1 & "MC|PingHost".equals(new String(bytebuf.readBytes(bytebuf.readShort() * 2).array(), Charsets.UTF_16BE));
                    int j = bytebuf.readUnsignedShort();
                    flag1 = flag1 & bytebuf.readUnsignedByte() >= 73;
                    flag1 = flag1 & 3 + bytebuf.readBytes(bytebuf.readShort() * 2).array().length + 4 == j;
                    flag1 = flag1 & bytebuf.readInt() <= 65535;
                    flag1 = flag1 & bytebuf.readableBytes() == 0;

                    if (!flag1)
                    {
                        return;
                    }

                    logger.debug("Ping: (1.6) from {}:{}", new Object[] {inetsocketaddress.getAddress(), Integer.valueOf(inetsocketaddress.getPort())});
                    String s1 = String.format("\u00a71\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d", new Object[] {Integer.valueOf(127), minecraftserver.getMinecraftVersion(), minecraftserver.getMOTD(), Integer.valueOf(minecraftserver.getCurrentPlayerCount()), Integer.valueOf(minecraftserver.getMaxPlayers())});
                    ByteBuf bytebuf1 = this.getStringBuffer(s1);

                    try
                    {
                        this.writeAndFlush(p_channelRead_1_, bytebuf1);
                    }
                    finally
                    {
                        bytebuf1.release();
                    }
            }

            bytebuf.release();
            flag = false;
            return;
        }
    }
    catch (RuntimeException var21)
    {
        return;
    }
    finally
    {
        if (flag)
        {
            bytebuf.resetReaderIndex();
            p_channelRead_1_.channel().pipeline().remove("legacy_query");
            p_channelRead_1_.fireChannelRead(p_channelRead_2_);
        }
    }
}
 
Example 18
Project: sctalk   File: PacketDecoder.java   Source Code and License Vote up 4 votes
@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws Exception {

    try {

        logger.debug("Protobuf decode started.");
        in.markReaderIndex();
        if (in.readableBytes() < 4) {
            logger.info("Readable Bytes length less than 4 bytes, ignored");
            in.resetReaderIndex();
            return;
        }

        DataBuffer dataBuf = new DataBuffer(in);

        IMHeader header = new IMHeader();
        header.decode(dataBuf);

        if (header.getLength() < 0) {
            ctx.close();
            logger.error("message length less than 0, channel closed");
            return;
        }

        ByteBuf byteBuf = ctx.alloc().buffer(header.getLength() - SysConstant.PROTOCOL_HEADER_LENGTH);

        in.readBytes(byteBuf);
        byte[] body;
        if (byteBuf.hasArray()) {
            body = byteBuf.array();
        } else {
            body = new byte[byteBuf.capacity()];
            byteBuf.readBytes(body);
        }

        MessageLite msg = ProtobufParseMap.getMessage(header.getServiceId(), header.getCommandId(), body);

        IMProtoMessage<MessageLite> protoMessage = new IMProtoMessage<>(header, msg);
        out.add(protoMessage);
        
        logger.debug("Received protobuf : length={}, commandId={}", header.getLength(), header.getCommandId());
    } catch (Exception e) {
        logger.error(ctx.channel().remoteAddress() + ",decode failed.", e);
    } finally {
        logger.debug("Protobuf decode finished.");
    }
}
 
Example 19
Project: netty-dovakin-android-client   File: NGLSProtocolCodec.java   Source Code and License Vote up 4 votes
/**
 * 协议解码
 * @param ctx
 * @param byteBuf
 * @param list
 * @throws Exception
 */
protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list)
        throws Exception {

    // 报文长度不足,退出
    if(byteBuf.readableBytes() < MIN_LENGTH) return;
    // 报文长度过长,判别为非法socket数据,丢弃
    if(byteBuf.readableBytes() > MAX_LENGTH) byteBuf.skipBytes(byteBuf.readableBytes());
    // 原始游标位置
    int index;
    // 开始读取协议包头
    while (true){
        index = byteBuf.readerIndex();
        byteBuf.markReaderIndex();
        // 成功解析协议包头
        if(byteBuf.readInt() == NGLSProtocol.getHEAD()){
            break;
        }
        // 过滤非协议数据
        byteBuf.resetReaderIndex();
        byteBuf.readByte();
        // 粘包处理
        if(byteBuf.readableBytes() < MIN_LENGTH){
            return;
        }
    }
    //解析协议ACTION类型
    int action = byteBuf.readInt();
    int length = byteBuf.readInt();
    // 粘包处理
    if(byteBuf.readableBytes() < length){
        byteBuf.readerIndex(index);
        return;
    }
    // 消息体读取
    byte[] content = new byte[length];
    byteBuf.readBytes(content);

    // 反序列化协议数据
    NGLSProtocol nglsProtocol = new NGLSProtocol(content.length, content);
    nglsProtocol.setTYPE(action);
    list.add(nglsProtocol);
}