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

The following are Jave code examples for showing how to use resetReaderIndex() 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: MooProject   File: ProtobufVarint32FrameDecoder.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 2
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 3
Project: FlexMC   File: MessageSplitter.java   Source Code and License Vote up 5 votes
@Override
protected void decode( ChannelHandlerContext channelHandlerContext, ByteBuf input, List<Object> output ) throws Exception {
    input.markReaderIndex();

    byte[] bytes = new byte[3];
    for ( int i = 0; i < bytes.length; i++ ) {
        if ( !input.isReadable() ) {
            input.resetReaderIndex();
            return;
        }
        bytes[i] = input.readByte();
        if ( bytes[i] >= 0 ) {
            ByteBuf buf = Unpooled.wrappedBuffer( bytes );
            try {
                int j = Message.readVarInt( buf );
                if ( input.readableBytes() < j ) {
                    input.resetReaderIndex();
                    return;
                }
                output.add( input.readBytes( j ) );
                return;
            } finally {
                buf.release();
            }
        }
    }
    throw new CorruptedFrameException( "length wider than 21-bit" );
}
 
Example 4
Project: BedrockProxy   File: Compression.java   Source Code and License Vote up 5 votes
/**
 * Decompresses a buffer.
 *
 * @param buffer the buffer to decompress
 * @return the decompressed buffer
 * @throws DataFormatException if data could not be inflated
 */
public static ByteBuf inflate(ByteBuf buffer) throws DataFormatException {
    // Ensure that this buffer is direct.
    ByteBuf source = null;
    ByteBuf decompressed = PooledByteBufAllocator.DEFAULT.directBuffer();

    try {
        if (!buffer.isDirect()) {
            // We don't have a direct buffer. Create one.
            ByteBuf temporary = PooledByteBufAllocator.DEFAULT.directBuffer();
            temporary.writeBytes(buffer);
            source = temporary;
        } else {
            source = buffer;
        }

        inflaterLocal.get().process(source, decompressed);
        decompressed.resetReaderIndex();
        return decompressed;
    } catch (DataFormatException e) {
        decompressed.release();
        throw e;
    } finally {
        if (source != null && source != buffer) {
            source.release();
        }
    }
}
 
Example 5
Project: L2J-Global   File: CryptCodec.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
{
	in.resetReaderIndex();
	_crypt.decrypt(in);
	in.readerIndex(in.writerIndex());
	out.add(in.copy(0, in.writerIndex()));
}
 
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: 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 8
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 9
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 10
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.
 *
 * @param buffer The source {@link ByteBuf}.
 */
public void putBytes(ByteBuf buffer) {
	byte[] bytes = new byte[buffer.readableBytes()];
	buffer.markReaderIndex();
	try {
		buffer.readBytes(bytes);
	} finally {
		buffer.resetReaderIndex();
	}
	putBytes(bytes);
}
 
Example 11
Project: L2J-Global   File: CryptCodec.java   Source Code and License Vote up 5 votes
@Override
protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out)
{
	// Check if there are any data to encrypt.
	if (!msg.isReadable())
	{
		return;
	}
	
	msg.resetReaderIndex();
	_crypt.encrypt(msg);
	msg.resetReaderIndex();
	out.writeBytes(msg);
}
 
Example 12
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 13
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 14
Project: candlelight   File: VarInt21FrameDecoder.java   Source Code and License Vote up 4 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception
{
	in.markReaderIndex();

	byte[] b = new byte[3];

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

		b[i] = in.readByte();

		if (b[i] >= 0)
		{
			try
			{
				int j = readVarInt21(in);
				if (in.readableBytes() >= j)
				{
					out.add(in.readBytes(j));
					return;
				}

				in.resetReaderIndex();
			}
			finally
			{
				in.release();
			}

			return;
		}
	}

	throw new CorruptedFrameException("length is greater than 21-bit varint");
}
 
Example 15
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 16
Project: DecompiledMinecraft   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: DecompiledMinecraft   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: 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 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);
}
 
Example 20
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.");
    }
}