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

The following are Jave code examples for showing how to use skipBytes() 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: message-broker   File: AmqpDecoder.java   Source Code and License Vote up 7 votes
private void processProtocolInitFrame(ByteBuf buffer, List<Object> out) {
    if (buffer.readableBytes() >= 8) {
        CharSequence protocolName = buffer.readCharSequence(4, CharsetUtil.US_ASCII);
        buffer.skipBytes(1);
        byte majorVersion = buffer.readByte();
        byte minorVersion = buffer.readByte();
        byte revision = buffer.readByte();

        if (!AMQP_PROTOCOL_IDENTIFIER.equals(protocolName)) {
            out.add(new AmqpBadMessage(new IllegalArgumentException("Unknown protocol name " +
                                                                           protocolName.toString())));
            currentState = State.BAD_MESSAGE;
        }

        out.add(new ProtocolInitFrame(majorVersion, minorVersion, revision));
    }
}
 
Example 2
Project: ClusterDeviceControlPlatform   File: CanFrameChannelInboundHandler.java   Source Code and License Vote up 6 votes
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
    if (errorCount != 0) {
        logger.warn("接收到错误的 CAN 帧数量:" + errorCount);
    }
    if (msg.readableBytes() % 13 != 0) {
        errorCount++;
        logger.warn("读取到非整数个 CAN 帧");
        return;
    }

    while (msg.readableBytes() >= 13) {
        int bodyLength = msg.readByte() & 0x0F;
        msg.skipBytes(1);
        int msgId = msg.readByte();
        int boxId = msg.readByte();
        int groupId = msg.readByte();
        IMessage message = handleMessage(msgId, groupId, boxId, bodyLength, msg);
        ctx.fireChannelRead(message);
    }
}
 
Example 3
Project: ProtocolSupportPocketStuff   File: ClientLoginPacket.java   Source Code and License Vote up 6 votes
@SuppressWarnings("resource")
@Override
public void readFromClientData(Connection connection, ByteBuf clientData) {
	protocolVersion = clientData.readInt(); //protocol version

	ByteBuf logindata = Unpooled.wrappedBuffer(ArraySerializer.readByteArray(clientData, connection.getVersion()));

	// skip chain data
	logindata.skipBytes(logindata.readIntLE());

	// decode skin data
	try {
		InputStream inputStream = new ByteBufInputStream(logindata, logindata.readIntLE());
		ByteArrayOutputStream result = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int length;
		while ((length = inputStream.read(buffer)) != -1) {
			result.write(buffer, 0, length);
		}
		clientPayload = decodeToken(result.toString("UTF-8"));
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 4
Project: ss-java   File: ShadowsocksRequestEncoder.java   Source Code and License Vote up 5 votes
@Override
protected void encode(ChannelHandlerContext ctx, SocksCmdRequest msg,
        ByteBuf out) throws Exception {
    msg.encodeAsByteBuf(out);
    out.skipBytes(3); // Simply skip first 3 bytes
    ctx.pipeline().remove(this);
}
 
Example 5
Project: incubator-plc4x   File: IsoOnTcpProtocol.java   Source Code and License Vote up 5 votes
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if(logger.isTraceEnabled()) {
        logger.trace("Got Data: {}", ByteBufUtil.hexDump(in));
    }
    // If at least 4 bytes are readable, peek into them (without changing the read position)
    // and get the packet length. Only if the available amount of readable bytes is larger or
    // equal to this, continue processing the rest.
    if(in.readableBytes() >= 4) {
        logger.debug("ISO on TCP Message received");
        // The ISO on TCP protocol is really simple and in this case the buffer length
        // will take care of the higher levels not reading more than is in the packet.
        // So we just gobble up the header and continue reading in higher levels.
        if (in.getByte(0) != ISO_ON_TCP_MAGIC_NUMBER) {
            logger.warn("Expecting ISO on TCP magic number: {}", ISO_ON_TCP_MAGIC_NUMBER);
            logger.debug("Got Data: " + ByteBufUtil.hexDump(in));
            exceptionCaught(ctx, new PlcProtocolException(
                String.format("Expecting ISO on TCP magic number: %02X", ISO_ON_TCP_MAGIC_NUMBER)));
            return;
        }
        // Byte 1 is a reserved byte set to 0x00
        short packetLength = in.getShort(2);
        if(in.readableBytes() >= packetLength) {
            // Skip the 4 bytes we peeked into manually.
            in.skipBytes(4);
            // Simply place the current buffer to the output ... the next handler will continue.
            ByteBuf payload = in.readBytes(packetLength - 4);
            out.add(new IsoOnTcpMessage(payload));
        }
    }
}
 
Example 6
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 7
Project: DovakinMQ   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<String>(null, numberOfBytesConsumed);
    }
    String s = buffer.toString(buffer.readerIndex(), size, CharsetUtil.UTF_8);
    buffer.skipBytes(size);
    numberOfBytesConsumed += size;
    return new Result<String>(s, numberOfBytesConsumed);
}
 
Example 8
Project: ClusterDeviceControlPlatform   File: CanFrameChannelInboundHandler.java   Source Code and License Vote up 5 votes
/**
 * 处理接收到的数据,转化为 Message 并送入下一级处理器
 *
 * @param ctx 处理器上下文
 * @param msg 待处理的已接收数据
 */

private void processByteBuf(ChannelHandlerContext ctx, ByteBuf msg) {
    while (msg.readableBytes() >= 13) {
        msg.skipBytes(2);
        int msgId = msg.readByte();
        int deviceId = msg.readByte();
        int groupId = msg.readByte();
        IMessage message = handleMessage(msgId, deviceId, groupId, msg);
        ctx.fireChannelRead(message);
    }
}
 
Example 9
Project: Re-Collector   File: PatternChunkSplitter.java   Source Code and License Vote up 4 votes
@Override
public Iterable<String> split(final ByteBuf buffer, final Charset charset, final boolean includeRemainingData) {
    return () -> new AbstractIterator<String>() {
        // TODO Might throw an exception if multibyte charset is used and buffer is not complete.
        //      Use CharsetDecoder to create a CharBuffer and match on that!
        private final String inputAsString = buffer.toString(charset);
        final Matcher matcher = pattern.matcher(inputAsString);
        private int positionInString = 0;

        @Override
        protected String computeNext() {
            try {
                if (!buffer.isReadable()) {
                    return endOfData();
                }
                if (matcher.find()) {
                    int firstByte = matcher.start();
                    if (firstByte == 0) {
                        // advance further, the buffer begins with our pattern.
                        if (matcher.find()) {
                            firstByte = matcher.start();
                        } else {
                            if (!includeRemainingData) {
                                // couldn't find the end of the entry (i.e. there wasn't a next line yet)
                                return endOfData();
                            } else {
                                // couldn't find another line, but we are asked to finish up, include everything that remains
                                return getRemainingContent();
                            }
                        }
                    }
                    if (firstByte == 0) {
                        // still haven't found a non-zero length string, keep waiting for more data.
                        return endOfData();
                    }
                    final String substring = inputAsString.substring(positionInString, firstByte);
                    positionInString = firstByte;
                    buffer.skipBytes(substring.getBytes(charset).length); // TODO performance
                    return substring;
                } else {
                    if (includeRemainingData) {
                        return getRemainingContent();
                    }
                    return endOfData();
                }
            } catch (IllegalStateException e) {
                // the cause contains the CharacterCodingException from the ChannelBuffer.toString() methods
                // this usually means the buffer ended with an incomplete encoding of a unicode character.
                // WHY U SO SUCK CHARACTER ENCODINGS?
                // we need to wait until more data is available
                return endOfData();
            } finally {
                buffer.discardReadBytes();
            }
        }

        private String getRemainingContent() {
            final ByteBuf channelBuffer = buffer.readBytes(buffer.readableBytes());
            return channelBuffer.toString(charset);
        }
    };
}
 
Example 10
Project: JRediClients   File: PubSubStatusDecoder.java   Source Code and License Vote up 4 votes
@Override
public Object decode(ByteBuf buf, State state) {
    String status = buf.toString(CharsetUtil.UTF_8);
    buf.skipBytes(2);
    return status;
}
 
Example 11
Project: JRediClients   File: StringReplayDecoder.java   Source Code and License Vote up 4 votes
@Override
public String decode(ByteBuf buf, State state) {
    String status = buf.readBytes(buf.bytesBefore((byte) '\r')).toString(CharsetUtil.UTF_8);
    buf.skipBytes(2);
    return status;
}
 
Example 12
Project: JRediClients   File: KeyValueObjectDecoder.java   Source Code and License Vote up 4 votes
@Override
public Object decode(ByteBuf buf, State state) {
    String status = buf.toString(CharsetUtil.UTF_8);
    buf.skipBytes(1);
    return status;
}
 
Example 13
Project: neoscada   File: PatternTimestampParser.java   Source Code and License Vote up 4 votes
@Override
public Calendar parseTimestamp ( final ByteBuf data )
{
    final int index = data.bytesBefore ( this.endMarker );
    if ( index < 0 )
    {
        throw new CodecException ( "Unable to find timestamp" );
    }

    final String timestampString = data.readSlice ( index ).toString ( this.charset );

    logger.debug ( "Timestamp string: '{}'", timestampString );

    final Matcher m = this.pattern.matcher ( timestampString );
    if ( !m.matches () )
    {
        throw new CodecException ( "Timestamp string does not match pattern: " + this.pattern.pattern () );
    }

    final int year = Integer.parseInt ( m.group ( "year" ) );
    final int month = Integer.parseInt ( m.group ( "month" ) ) - 1;
    final int day = Integer.parseInt ( m.group ( "day" ) );
    final int hour = Integer.parseInt ( m.group ( "hour" ) );
    final int minute = Integer.parseInt ( m.group ( "minute" ) );
    final int second = Integer.parseInt ( m.group ( "second" ) );
    final int ms = Integer.parseInt ( m.group ( "subsec" ) ) / 1000;

    TimeZone timezone = TimeZone.getDefault ();
    final String tz = m.group ( "tz" );
    if ( !tz.isEmpty () )
    {
        // FIXME: implement
        if ( "Z".equals ( tz ) )
        {
            timezone = TimeZone.getTimeZone ( "UTC" );
        }
        else
        {
            timezone = TimeZone.getTimeZone ( "GMT" + tz );
        }
    }

    final Calendar c = new GregorianCalendar ( year, month, day, hour, minute, second );
    c.setTimeZone ( timezone );
    c.set ( Calendar.MILLISECOND, ms );

    // skip marker byte
    data.skipBytes ( 1 );

    return c;
}
 
Example 14
Project: JavaNRPC   File: NrpcChannel.java   Source Code and License Vote up 4 votes
public byte[] recvRpcMessage(Socket socket) throws IOException, java.net.SocketTimeoutException {
    BufferedInputStream dataInput = new BufferedInputStream(socket.getInputStream());
    do {
        byte[] temp = new byte[Constants.BUFFER_SIZE];
        int n = dataInput.read(temp);
        if(n>0){
            readBuffer.write(temp,0,n);
        }
        if (n < 0 || n < Constants.BUFFER_SIZE) {
            break;
        }
    } while (true);
    byte[] readContent = readBuffer.toByteArray();
    ByteBuf in = Unpooled.buffer(readContent.length);
    in.writeBytes(readContent);
    int readable = in.readableBytes();
    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!");
            closeSocket();
            throw new IOException("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) {
            logger.warn("Not enough data");
            closeSocket();
            throw new IOException("Not enough data!");
        }
        // 开始解码报文
        in.skipBytes(Constants.HEADER_SIZE);
        byte[] dest = new byte[totalSize - Constants.HEADER_SIZE];
        in.readBytes(dest);
        return dest;
    } else {
        logger.warn("Not enough data header");
        closeSocket();
        throw new IOException("Not enough data header!");
    }
}
 
Example 15
Project: redis-cluster-watchdog   File: ClusterMessageDecoder.java   Source Code and License Vote up 4 votes
protected void decodeMessageV1(ClusterMessage hdr, ByteBuf in) {
    hdr.port = in.readUnsignedShort();
    hdr.type = in.readUnsignedShort();
    hdr.count = in.readUnsignedShort();
    hdr.currentEpoch = in.readLong();
    hdr.configEpoch = in.readLong();
    hdr.offset = in.readLong();
    hdr.name = truncate(in, CLUSTER_NODE_NULL_NAME);
    in.readBytes(hdr.slots);
    hdr.master = truncate(in, CLUSTER_NODE_NULL_NAME);
    hdr.ip = truncate(in, CLUSTER_NODE_NULL_IP);
    in.skipBytes(34);
    hdr.busPort = in.readUnsignedShort();
    hdr.flags = in.readUnsignedShort();
    hdr.state = valueOf(in.readByte());
    in.readBytes(hdr.messageFlags);
    switch (hdr.type) {
        case CLUSTERMSG_TYPE_PING:
        case CLUSTERMSG_TYPE_PONG:
        case CLUSTERMSG_TYPE_MEET:
            for (int i = 0; i < hdr.count; i++) {
                ClusterMessageDataGossip gossip = new ClusterMessageDataGossip();
                gossip.name = truncate(in, CLUSTER_NODE_NULL_NAME);
                gossip.pingTime = in.readInt() * 1000L;
                gossip.pongTime = in.readInt() * 1000L;
                gossip.ip = truncate(in, CLUSTER_NODE_NULL_IP);
                gossip.port = in.readUnsignedShort();
                gossip.busPort = in.readUnsignedShort();
                gossip.flags = in.readUnsignedShort();
                in.skipBytes(4);
                hdr.data.gossips.add(gossip);
            }
            break;
        case CLUSTERMSG_TYPE_FAIL:
            hdr.data.fail.name = truncate(in, CLUSTER_NODE_NULL_NAME);
            break;
        case CLUSTERMSG_TYPE_PUBLISH:
            hdr.data.publish.channelLength = in.readInt();
            hdr.data.publish.messageLength = in.readInt();
            in.readBytes(hdr.data.publish.bulkData);
            break;
        case CLUSTERMSG_TYPE_UPDATE:
            hdr.data.config.configEpoch = in.readLong();
            hdr.data.config.name = truncate(in, CLUSTER_NODE_NULL_NAME);
            in.readBytes(hdr.data.config.slots);
            break;
        default:
            break;
    }
}
 
Example 16
Project: message-broker   File: ContentFrame.java   Source Code and License Vote up 4 votes
public static ContentFrame parse(ByteBuf buf, int channel, long payloadSize) {
    ByteBuf payload = buf.retainedSlice(buf.readerIndex(), (int) payloadSize);
    buf.skipBytes((int) payloadSize);

    return new ContentFrame(channel, payloadSize, payload);
}
 
Example 17
Project: netto_rpc   File: NettoFrameDecoder.java   Source Code and License Vote up 4 votes
@SuppressWarnings("unused")
@Override
   protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
       // 1.判断in.readerIndex
       int idx = in.readerIndex();
       int wrtIdx = in.writerIndex();

       if (wrtIdx > maxRequestSize) {
           // buffer size exceeded maxObjectLength; discarding the complete
           // buffer.
           in.skipBytes(in.readableBytes());
           throw new TooLongFrameException(
                   "object length exceeds " + maxRequestSize + ": " + wrtIdx + " bytes discarded");
       }

       for (; idx < wrtIdx; idx++) {
           byte c = in.getByte(idx);
           if (Character.isWhitespace(c)) {
               in.skipBytes(1);
           } else {
               break;
           }
       }

       if (in.readableBytes() >= NettoFrame.HEADER_LENGTH) {
           byte[] headerInfo = new byte[NettoFrame.HEADER_LENGTH];
           Arrays.fill(headerInfo, (byte) ' ');

           in.getBytes(in.readerIndex(), headerInfo);
           String headerStr = new String(headerInfo, "UTF-8");
           if (headerStr.startsWith(NettoFrame.NETTO_HEADER_START)) {

               try {
                   String headerInfoContent = headerStr.substring(NettoFrame.NETTO_HEADER_START.length());
                   String[] headerSections = headerInfoContent.split("/");
                   if (headerSections.length == 3) {
                       String version = headerSections[0];
                       String headerContentSizeAsString = headerSections[1].trim();
                       String bodySizeAsString = headerSections[2].trim();
                       int headerContentSize = Integer.parseInt(headerContentSizeAsString);
                       int bodySize = Integer.parseInt(bodySizeAsString);
                       if (in.readableBytes() >= bodySize + headerContentSize + NettoFrame.HEADER_LENGTH) {
                           ByteBuf headerContent = in.retainedSlice(NettoFrame.HEADER_LENGTH, headerContentSize);
                           ByteBuf body = in.retainedSlice(NettoFrame.HEADER_LENGTH + headerContentSize, bodySize);
                           NettoFrame nettoMessage = new NettoFrame();
                           nettoMessage.setBodySize(bodySize);
                           nettoMessage.setBody(body);
                           nettoMessage.setHeaderContent(headerContent);
                           nettoMessage.setHeaderContentSize(headerContentSize);
                           out.add(nettoMessage);
                           in.readerIndex(NettoFrame.HEADER_LENGTH + headerContentSize + bodySize);
                       }
                   } else {
                       in.skipBytes(in.readableBytes());
                       throw new NettoDecoderException("header parse error:" + headerStr);
                   }
               } catch (Throwable t) {
                   logger.error("decode error:"+headerStr,t);
                   in.skipBytes(in.readableBytes());
                   throw new NettoDecoderException("decode error:" + headerStr);
                   
               }

           } else {

               in.skipBytes(in.readableBytes());
               throw new NettoDecoderException("header start error:" + headerStr);
           }

       }

   }
 
Example 18
Project: ditb   File: AsyncServerResponseHandler.java   Source Code and License Vote up 4 votes
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  ByteBuf inBuffer = (ByteBuf) msg;
  ByteBufInputStream in = new ByteBufInputStream(inBuffer);
  int totalSize = inBuffer.readableBytes();
  try {
    // Read the header
    RPCProtos.ResponseHeader responseHeader = RPCProtos.ResponseHeader.parseDelimitedFrom(in);
    int id = responseHeader.getCallId();
    AsyncCall call = channel.removePendingCall(id);
    if (call == null) {
      // So we got a response for which we have no corresponding 'call' here on the client-side.
      // We probably timed out waiting, cleaned up all references, and now the server decides
      // to return a response.  There is nothing we can do w/ the response at this stage. Clean
      // out the wire of the response so its out of the way and we can get other responses on
      // this connection.
      int readSoFar = IPCUtil.getTotalSizeWhenWrittenDelimited(responseHeader);
      int whatIsLeftToRead = totalSize - readSoFar;

      // This is done through a Netty ByteBuf which has different behavior than InputStream.
      // It does not return number of bytes read but will update pointer internally and throws an
      // exception when too many bytes are to be skipped.
      inBuffer.skipBytes(whatIsLeftToRead);
      return;
    }

    if (responseHeader.hasException()) {
      RPCProtos.ExceptionResponse exceptionResponse = responseHeader.getException();
      RemoteException re = createRemoteException(exceptionResponse);
      if (exceptionResponse.getExceptionClassName().
          equals(FatalConnectionException.class.getName())) {
        channel.close(re);
      } else {
        call.setFailed(re);
      }
    } else {
      Message value = null;
      // Call may be null because it may have timedout and been cleaned up on this side already
      if (call.responseDefaultType != null) {
        Message.Builder builder = call.responseDefaultType.newBuilderForType();
        ProtobufUtil.mergeDelimitedFrom(builder, in);
        value = builder.build();
      }
      CellScanner cellBlockScanner = null;
      if (responseHeader.hasCellBlockMeta()) {
        int size = responseHeader.getCellBlockMeta().getLength();
        byte[] cellBlock = new byte[size];
        inBuffer.readBytes(cellBlock, 0, cellBlock.length);
        cellBlockScanner = channel.client.createCellScanner(cellBlock);
      }
      call.setSuccess(value, cellBlockScanner);
      call.callStats.setResponseSizeBytes(totalSize);
    }
  } catch (IOException e) {
    // Treat this as a fatal condition and close this connection
    channel.close(e);
  } finally {
    inBuffer.release();
  }
}
 
Example 19
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 20
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);
}