當前位置: 首頁>>代碼示例>>Java>>正文


Java ByteBuf.skipBytes方法代碼示例

本文整理匯總了Java中io.netty.buffer.ByteBuf.skipBytes方法的典型用法代碼示例。如果您正苦於以下問題:Java ByteBuf.skipBytes方法的具體用法?Java ByteBuf.skipBytes怎麽用?Java ByteBuf.skipBytes使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在io.netty.buffer.ByteBuf的用法示例。


在下文中一共展示了ByteBuf.skipBytes方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: processProtocolInitFrame

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
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));
    }
}
 
開發者ID:wso2,項目名稱:message-broker,代碼行數:18,代碼來源:AmqpDecoder.java

示例2: channelRead0

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@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);
    }
}
 
開發者ID:bitkylin,項目名稱:ClusterDeviceControlPlatform,代碼行數:22,代碼來源:CanFrameChannelInboundHandler.java

示例3: readFromClientData

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@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();
	}
}
 
開發者ID:ProtocolSupport,項目名稱:ProtocolSupportPocketStuff,代碼行數:25,代碼來源:ClientLoginPacket.java

示例4: encode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@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);
}
 
開發者ID:zhoulifu,項目名稱:ss-java,代碼行數:8,代碼來源:ShadowsocksRequestEncoder.java

示例5: decode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@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));
        }
    }
}
 
開發者ID:apache,項目名稱:incubator-plc4x,代碼行數:32,代碼來源:IsoOnTcpProtocol.java

示例6: decode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@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);
  }
}
 
開發者ID:dremio,項目名稱:dremio-oss,代碼行數:56,代碼來源:MessageDecoder.java

示例7: decodeString

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
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);
}
 
開發者ID:Dovakin-IO,項目名稱:DovakinMQ,代碼行數:15,代碼來源:MqttDecoder.java

示例8: processByteBuf

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
/**
 * 處理接收到的數據,轉化為 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);
    }
}
 
開發者ID:bitkylin,項目名稱:ClusterDeviceControlPlatform,代碼行數:18,代碼來源:CanFrameChannelInboundHandler.java

示例9: split

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@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);
        }
    };
}
 
開發者ID:DevOpsStudio,項目名稱:Re-Collector,代碼行數:63,代碼來源:PatternChunkSplitter.java

示例10: decode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@Override
public Object decode(ByteBuf buf, State state) {
    String status = buf.toString(CharsetUtil.UTF_8);
    buf.skipBytes(2);
    return status;
}
 
開發者ID:qq1588518,項目名稱:JRediClients,代碼行數:7,代碼來源:PubSubStatusDecoder.java

示例11: decode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@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;
}
 
開發者ID:qq1588518,項目名稱:JRediClients,代碼行數:7,代碼來源:StringReplayDecoder.java

示例12: decode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@Override
public Object decode(ByteBuf buf, State state) {
    String status = buf.toString(CharsetUtil.UTF_8);
    buf.skipBytes(1);
    return status;
}
 
開發者ID:qq1588518,項目名稱:JRediClients,代碼行數:7,代碼來源:KeyValueObjectDecoder.java

示例13: parseTimestamp

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@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;
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:52,代碼來源:PatternTimestampParser.java

示例14: recvRpcMessage

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
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!");
    }
}
 
開發者ID:kevin-xu-158,項目名稱:JavaNRPC,代碼行數:49,代碼來源:NrpcChannel.java

示例15: decodeMessageV1

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
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;
    }
}
 
開發者ID:leonchen83,項目名稱:redis-cluster-watchdog,代碼行數:51,代碼來源:ClusterMessageDecoder.java


注:本文中的io.netty.buffer.ByteBuf.skipBytes方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。