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

The following are Jave code examples for showing how to use readBytes() 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: ClusterDeviceControlPlatform   File: FrameRecognitionInBoundHandler.java   Source Code and License Vote up 6 votes
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception {
    while (true) {
        if (byteBuf.readableBytes() < FrameSetting.FRAME_HEAD_LENGTH) {
            return;
        }
        if (byteBuf.readByte() != FrameSetting.MAJOR_FRAME_HEAD_1
                || byteBuf.readByte() != FrameSetting.MAJOR_FRAME_HEAD_2) {
            return;
        }
        int groupId = byteBuf.readByte() & 0xFF;
        int msgId = byteBuf.readByte() & 0xFF;
        int deviceId = byteBuf.readByte() & 0xFF;
        int backupMsg = byteBuf.readByte() & 0xFF;
        int dataLength = byteBuf.readShort() & 0xFF;
        FrameMajorHeader headMsg = new FrameMajorHeader(msgId, groupId, deviceId, dataLength, backupMsg);
        ByteBuf subBuf = ctx.alloc().buffer(dataLength);
        byteBuf.readBytes(subBuf, dataLength);
        ctx.fireChannelRead(new FrameMajor(headMsg, subBuf));
    }
}
 
Example 2
Project: cr-private-server   File: PacketDecoder.java   Source Code and License Vote up 6 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	if (!hasHeader) {
		if (in.readableBytes() >= 7) {
			short id = in.readShort();
			int payloadLength = in.readMedium();
			short version = in.readShort();

			hasHeader = true;
			header.id = id;
			header.payload = new byte[payloadLength];
		}
	} else {
		if (in.readableBytes() >= header.payload.length) {
			in.readBytes(header.payload);
			hasHeader = false;

			crypto.decryptPacket(header);

			ClientMessage message = processPacket();
			if (message != null) {
				out.add(message);
			}
		}
	}
}
 
Example 3
Project: happylifeplat-transaction   File: AbstractMessageDecoder.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    if (in.readableBytes() < AbstractMessageDecoder.MESSAGE_LENGTH) {
        return;
    }

    in.markReaderIndex();
    int messageLength = in.readInt();

    if (messageLength < 0) {
        ctx.close();
    }

    if (in.readableBytes() < messageLength) {
        in.resetReaderIndex();
    } else {
        byte[] messageBody = new byte[messageLength];
        in.readBytes(messageBody);

        try {
            Object obj = util.decode(messageBody);
            out.add(obj);
        } catch (IOException ex) {
            Logger.getLogger(AbstractMessageDecoder.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
 
Example 4
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 5
Project: JungleTree   File: OutboundRequestProcessor.java   Source Code and License Vote up 5 votes
private void writePackets(Packet[] packets) {
    for (Packet packet : packets) {
        packetQueue.remove(packet);
    }

    if (packets.length == 0) {
        return;
    }

    writer.writePackets(packets);
    byte[] batch = writer.getPacketBytes();

    if (client.getProtocolEncryption() != null) {
        batch = client.getProtocolEncryption().encryptInputForClient(batch);
    }

    ByteBuf buf = ByteBufAllocator.DEFAULT.directBuffer(batch.length + 1);
    buf.writeByte((byte) PACKET_BATCH_ID);
    buf.writeBytes(batch);

    byte[] result = new byte[buf.readableBytes()];
    buf.readBytes(result);

    writer.reset();
    log.trace("Sending batch packet");

    client.getConnection().send(result);
}
 
Example 6
Project: simulacron   File: ByteBufCodec.java   Source Code and License Vote up 5 votes
@Override
public InetAddress readInetAddr(ByteBuf source) {
  int len = readByte(source);
  byte[] addr = new byte[len];
  source.readBytes(addr);
  try {
    return InetAddress.getByAddress(addr);
  } catch (UnknownHostException uhe) {
    throw new IllegalArgumentException(uhe);
  }
}
 
Example 7
Project: nearenough   File: RtMessage.java   Source Code and License Vote up 5 votes
private Map<RtTag, byte[]> extractSingleMapping(ByteBuf msg) {
  long uintTag = msg.readUnsignedInt();
  RtTag tag = RtTag.fromUnsignedInt((int) uintTag);

  byte[] value = new byte[msg.readableBytes()];
  msg.readBytes(value);

  return Collections.singletonMap(tag, value);
}
 
Example 8
Project: proxyee-down   File: ByteUtil.java   Source Code and License Vote up 5 votes
public static ByteBuf insertText(ByteBuf byteBuf, int index, String str) {
  byte[] begin = new byte[index + 1];
  byte[] end = new byte[byteBuf.readableBytes() - begin.length];
  byteBuf.readBytes(begin);
  byteBuf.readBytes(end);
  byteBuf.writeBytes(begin);
  byteBuf.writeBytes(stringToBytes(str));
  byteBuf.writeBytes(end);
  return byteBuf;
}
 
Example 9
Project: j1st-mqtt   File: MqttDecoder.java   Source Code and License Vote up 5 votes
private static Result<String> decodeString(ByteBuf buffer, int minBytes, int maxBytes) {
    final Result<Integer> decodedSize = decodeMsbLsb(buffer);
    int size = decodedSize.value;
    int numberOfBytesConsumed = decodedSize.numberOfBytesConsumed;
    if (size < minBytes || size > maxBytes) {
        buffer.skipBytes(size);
        numberOfBytesConsumed += size;
        return new Result<>(null, numberOfBytesConsumed);
    }
    ByteBuf buf = buffer.readBytes(size);
    numberOfBytesConsumed += size;
    return new Result<>(buf.toString(CharsetUtil.UTF_8), numberOfBytesConsumed);
}
 
Example 10
Project: BaseClient   File: NettyCompressionEncoder.java   Source Code and License Vote up 5 votes
protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception
{
    int i = p_encode_2_.readableBytes();
    PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_);

    if (i < this.treshold)
    {
        packetbuffer.writeVarIntToBuffer(0);
        packetbuffer.writeBytes(p_encode_2_);
    }
    else
    {
        byte[] abyte = new byte[i];
        p_encode_2_.readBytes(abyte);
        packetbuffer.writeVarIntToBuffer(abyte.length);
        this.deflater.setInput(abyte, 0, i);
        this.deflater.finish();

        while (!this.deflater.finished())
        {
            int j = this.deflater.deflate(this.buffer);
            packetbuffer.writeBytes((byte[])this.buffer, 0, j);
        }

        this.deflater.reset();
    }
}
 
Example 11
Project: BaseClient   File: NettyCompressionEncoder.java   Source Code and License Vote up 5 votes
protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception
{
    int i = p_encode_2_.readableBytes();
    PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_);

    if (i < this.treshold)
    {
        packetbuffer.writeVarIntToBuffer(0);
        packetbuffer.writeBytes(p_encode_2_);
    }
    else
    {
        byte[] abyte = new byte[i];
        p_encode_2_.readBytes(abyte);
        packetbuffer.writeVarIntToBuffer(abyte.length);
        this.deflater.setInput(abyte, 0, i);
        this.deflater.finish();

        while (!this.deflater.finished())
        {
            int j = this.deflater.deflate(this.buffer);
            packetbuffer.writeBytes((byte[])this.buffer, 0, j);
        }

        this.deflater.reset();
    }
}
 
Example 12
Project: DecompiledMinecraft   File: NettyEncryptionTranslator.java   Source Code and License Vote up 5 votes
private byte[] func_150502_a(ByteBuf p_150502_1_)
{
    int i = p_150502_1_.readableBytes();

    if (this.field_150505_b.length < i)
    {
        this.field_150505_b = new byte[i];
    }

    p_150502_1_.readBytes((byte[])this.field_150505_b, 0, i);
    return this.field_150505_b;
}
 
Example 13
Project: CustomWorldGen   File: NettyCompressionEncoder.java   Source Code and License Vote up 5 votes
protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception
{
    int i = p_encode_2_.readableBytes();
    PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_);

    if (i < this.threshold)
    {
        packetbuffer.writeVarIntToBuffer(0);
        packetbuffer.writeBytes(p_encode_2_);
    }
    else
    {
        byte[] abyte = new byte[i];
        p_encode_2_.readBytes(abyte);
        packetbuffer.writeVarIntToBuffer(abyte.length);
        this.deflater.setInput(abyte, 0, i);
        this.deflater.finish();

        while (!this.deflater.finished())
        {
            int j = this.deflater.deflate(this.buffer);
            packetbuffer.writeBytes((byte[])this.buffer, 0, j);
        }

        this.deflater.reset();
    }
}
 
Example 14
Project: dremio-oss   File: MessageDecoder.java   Source Code and License Vote up 4 votes
/**
 * We decode the message in the same context as the length decoding to better
 * manage running out of memory. We decode the rpc header using heap memory
 * (expected to always be available) so that we can propagate a error message
 * with correct coordination id to sender rather than failing the channel.
 *
 * @param ctx The channel context.
 * @param frame The Frame of the message we're processing.
 * @param length The length of the frame.
 * @throws Exception Code should only throw corrupt channel messages, causing the channel to close.
 */
private InboundRpcMessage decodeMessage(final ChannelHandlerContext ctx, final ByteBuf frame, final int length) throws Exception {
  // now, we know the entire message is in the buffer and the buffer is constrained to this message. Additionally,
  // this process should avoid reading beyond the end of this buffer so we inform the ByteBufInputStream to throw an
  // exception if be go beyond readable bytes (as opposed to blocking).
  final ByteBufInputStream is = new ByteBufInputStream(frame, length);

  // read the rpc header, saved in delimited format.
  checkTag(is, RpcEncoder.HEADER_TAG);
  final RpcHeader header = RpcHeader.parseDelimitedFrom(is);


  // read the protobuf body into a buffer.
  checkTag(is, RpcEncoder.PROTOBUF_BODY_TAG);
  final int pBodyLength = readRawVarint32(is);

  final byte[] pBody = new byte[pBodyLength];
  frame.readBytes(pBody);

  ByteBuf dBody = null;

  // read the data body.
  if (frame.readableBytes() > 0) {

    if (RpcConstants.EXTRA_DEBUGGING) {
      logger.debug("Reading raw body, buffer has {} bytes available.", frame.readableBytes());
    }

    checkTag(is, RpcEncoder.RAW_BODY_TAG);
    final int dBodyLength = readRawVarint32(is);

    if (frame.readableBytes() != dBodyLength) {
      throw new CorruptedFrameException(String.format("Expected to receive a raw body of %d bytes but received a buffer with %d bytes.", dBodyLength, frame.readableBytes()));
    }


    try {
      dBody = allocator.buffer(dBodyLength);
      // need to make buffer copy, otherwise netty will try to refill this buffer if we move the readerIndex forward...
      // TODO: Can we avoid this copy?
      dBody.writeBytes(frame, frame.readerIndex(), dBodyLength);

    } catch (OutOfMemoryException e) {
      sendOutOfMemory(e, ctx, header.getCoordinationId());
      return null;
    }

    if (RpcConstants.EXTRA_DEBUGGING) {
      logger.debug("Read raw body of length ", dBodyLength);
    }

  }else{
    if (RpcConstants.EXTRA_DEBUGGING) {
      logger.debug("No need to read raw body, no readable bytes left.");
    }
  }

  InboundRpcMessage m = new InboundRpcMessage(header.getMode(), header.getRpcType(), header.getCoordinationId(),
      pBody, dBody);
  return m;
}
 
Example 15
Project: sstable-adaptor   File: CBUtil.java   Source Code and License Vote up 4 votes
public static UUID readUUID(ByteBuf cb)
{
    byte[] bytes = new byte[16];
    cb.readBytes(bytes);
    return UUIDGen.getUUID(ByteBuffer.wrap(bytes));
}
 
Example 16
Project: Nukkit-Java9   File: SessionManager.java   Source Code and License Vote up 4 votes
private boolean receivePacket() throws Exception {
    DatagramPacket datagramPacket = this.socket.readPacket();
    if (datagramPacket != null) {
        // Check this early
        try {
            String source = datagramPacket.sender().getHostString();
            currentSource = source; //in order to block address
            if (this.block.containsKey(source)) {
                return true;
            }

            if (this.ipSec.containsKey(source)) {
                this.ipSec.put(source, this.ipSec.get(source) + 1);
            } else {
                this.ipSec.put(source, 1);
            }

            ByteBuf byteBuf = datagramPacket.content();
            if (byteBuf.readableBytes() == 0) {
                // Exit early to process another packet
                return true;
            }
            byte[] buffer = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(buffer);
            int len = buffer.length;
            int port = datagramPacket.sender().getPort();

            this.receiveBytes += len;

            byte pid = buffer[0];

            if (pid == UNCONNECTED_PONG.ID) {
                return false;
            }

            Packet packet = this.getPacketFromPool(pid);
            if (packet != null) {
                packet.buffer = buffer;
                this.getSession(source, port).handlePacket(packet);
                return true;
            } else if (pid == UNCONNECTED_PING.ID) {
                packet = new UNCONNECTED_PING();
                packet.buffer = buffer;
                packet.decode();

                UNCONNECTED_PONG pk = new UNCONNECTED_PONG();
                pk.serverID = this.getID();
                pk.pingID = ((UNCONNECTED_PING) packet).pingID;
                pk.serverName = this.getName();
                this.sendPacket(pk, source, port);
            } else if (buffer.length != 0) {
                this.streamRAW(source, port, buffer);
                return true;
            } else {
                return false;
            }
        } finally {
            datagramPacket.release();
        }
    }

    return false;
}
 
Example 17
Project: JRediClients   File: ByteArrayCodec.java   Source Code and License Vote up 4 votes
@Override
public Object decode(ByteBuf buf, State state) {
    byte[] result = new byte[buf.readableBytes()];
    buf.readBytes(result);
    return result;
}
 
Example 18
Project: JavaNRPC   File: NrpcDecoder.java   Source Code and License Vote up 4 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    int readable = in.readableBytes();
    if (readable > Constants.MAX_FRAME_SIZE) {
        logger.error("Frame too big : {}, max is {}",new Object[]{readable,Constants.MAX_FRAME_SIZE});
        in.skipBytes(readable);
        ctx.close();
        throw new TooLongFrameException("Frame too big!");
    }
    int pos = 0;
    if(readable >= Constants.HEADER_SIZE){
        // 检查Magic number
        if(in.getByte(pos) == 'N' && in.getByte(pos+1) == 'R' && in.getByte(pos+2) == 'P' && in.getByte(pos+3) == 'C'){
        }else{
            logger.error("Wrong magic number!");
            in.skipBytes(readable);
            ctx.close();
            throw new WrongMagicNumException("Wrong magic number!");
        }
        int totalSize = (int)in.getUnsignedInt(pos+4);
        byte type = in.getByte(pos+8);
        if(type == 0){
            logger.debug("one request");
        }else if(type == 1){
            logger.debug("one response");
        }
        if(readable < totalSize ){
            return;
        }
        // 开始解码报文
        try{
            in.skipBytes(Constants.HEADER_SIZE);
            byte[] dest = new byte[totalSize-Constants.HEADER_SIZE];
            in.readBytes(dest);
            ByteArrayInputStream destByteInputStream = new ByteArrayInputStream(dest);
            NrpcMeta nrpcMeta = NrpcMeta.parseFrom(destByteInputStream);
            out.add(nrpcMeta);
        }catch(Exception ex) {
            logger.error(ex.getMessage(), ex);
            ctx.close();
            throw new DecodeException("NrpcMeta decode failed!");
        }
    }
}
 
Example 19
Project: jsf-sdk   File: DubboProtocol.java   Source Code and License Vote up 4 votes
@Override
public Object decode(ByteBuf datas, Class clazz) {
    byte[] databs = new byte[datas.readableBytes()];
    datas.readBytes(databs);
    return codec.decode(databs, clazz);
}
 
Example 20
Project: jsf-sdk   File: ProtocolUtil.java   Source Code and License Vote up 4 votes
public static BaseMessage decode(ByteBuf byteBuf){
        MessageHeader header = null;
        Integer msgLength = byteBuf.readableBytes() + 6;//magiccode + msg length(4 byte)
        BaseMessage msg = null;
        ByteBuf deCompress = null;
        try {
            Short headerLength = byteBuf.readShort();
//            int readerIndex = byteBuf.readerIndex();
//            if(readerIndex > byteBuf.readableBytes()){
//                throw new JSFCodecException("codecError:header length error.");
//            }
            //ByteBuf headerBuf = byteBuf.slice(readerIndex,headerLength);
            //byteBuf.skipBytes(headerLength);
            header = CodecUtils.decodeHeader(byteBuf, headerLength);
            header.setHeaderLength(headerLength);
            //是否需要解压
            int compType = header.getCompressType();
            if (compType > 0) {
                if(logger.isTraceEnabled()) {
                    logger.trace("msgId [{}] is deCompressed with processType {}",
                            header.getMsgId(), Constants.CompressType.valueOf((byte) compType));
                }

                byte[] desc = new byte[byteBuf.readableBytes()];
                byteBuf.readBytes(desc);
                byte[] deCom = CompressUtil.deCompress(desc, (byte)compType);
                deCompress = PooledBufHolder.getBuffer(deCom.length);
                deCompress.writeBytes(deCom);
                byteBuf.release();

                header.setLength(deCompress.readableBytes() + 6 + headerLength);
                msg = enclosure(deCompress,header);
            } else {
                header.setLength(msgLength);
                msg = enclosure(byteBuf,header);
            }
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
            RpcException rpcException = ExceptionUtils.handlerException(header, e);
            byteBuf.release();//release the byteBuf when decode hit on error
            if (deCompress != null) deCompress.release();
            throw rpcException;
        }
        return msg;
    }