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


Java ByteBuf.getBytes方法代碼示例

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


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

示例1: readBytes

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@Override
public ByteBuffer readBytes(ByteBuf source) {
  int len = readInt(source);
  if (len < 0) {
    return null;
  }

  ByteBuf slice = source.readSlice(len);
  // if direct byte buffer, return underlying nioBuffer.
  if (slice.isDirect()) {
    return slice.nioBuffer();
  }
  // otherwise copy to a byte array and wrap it.
  final byte[] out = new byte[slice.readableBytes()];
  source.getBytes(source.readerIndex(), out, 0, len);
  return ByteBuffer.wrap(out);
}
 
開發者ID:datastax,項目名稱:simulacron,代碼行數:18,代碼來源:ByteBufCodec.java

示例2: decode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@Override
protected void decode(ChannelHandlerContext ctx, NettoFrame msg, List<Object> out) throws Exception {
    ByteBuf headerContent = msg.getHeaderContent();
    byte[] headerBytesBuf = new byte[msg.getHeaderContentSize()];
    headerContent.getBytes(headerContent.readerIndex(), headerBytesBuf);
    NettoMessage message = new NettoMessage();
    ByteBuf body = msg.getBody();
    byte[] bodyBytesBuf = new byte[msg.getBodySize()];        
    body.getBytes(body.readerIndex(), bodyBytesBuf);
    
    Map<String,String> headers = this.decoderHeader(new String(headerBytesBuf));

    message.setBody(bodyBytesBuf);
    message.setHeaders(headers);
    out.add(message);
    
    
}
 
開發者ID:sylinklee,項目名稱:netto_rpc,代碼行數:19,代碼來源:NettoMessageDecoder.java

示例3: encode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
public ByteBuf encode(ByteBufAllocator allocator, SocksCmdRequest msg) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("encode target address");
    }

    ByteBuf buf = allocator.directBuffer();
    msg.encodeAsByteBuf(buf);
    buf.skipBytes(3);

    if (LOG.isTraceEnabled()) {
        byte[] bytes = new byte[buf.readableBytes()];
        buf.getBytes(buf.readerIndex(), bytes);
    }

    return buf;
}
 
開發者ID:tridays,項目名稱:netty-socks,代碼行數:17,代碼來源:SSocksAddressEncoder.java

示例4: decode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    final byte[] array;
    final int offset;
    final int length = msg.readableBytes();
    if (msg.hasArray()) {
        array = msg.array();
        offset = msg.arrayOffset() + msg.readerIndex();
    } else {
        array = new byte[length];
        msg.getBytes(msg.readerIndex(), array, 0, length);
        offset = 0;
    }

    if (extensionRegistry == null) {
        if (HAS_PARSER) {
            out.add(prototype.getParserForType().parseFrom(array, offset, length));
        } else {
            out.add(prototype.newBuilderForType().mergeFrom(array, offset, length).build());
        }
    } else {
        if (HAS_PARSER) {
            out.add(prototype.getParserForType().parseFrom(array, offset, length, extensionRegistry));
        } else {
            out.add(prototype.newBuilderForType().mergeFrom(array, offset, length, extensionRegistry).build());
        }
    }
}
 
開發者ID:ninelook,項目名稱:wecard-server,代碼行數:29,代碼來源:ProtobufDecoder.java

示例5: decode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
	final int length = msg.readableBytes();
	final byte[] array = new byte[length];
	msg.getBytes(msg.readerIndex(), array, 0, length);
	out.add(new MessagePack().read(array, Packet.class));
}
 
開發者ID:ctodb,項目名稱:push,代碼行數:8,代碼來源:MsgPackDecode.java

示例6: dotStuffUsingByteBuf

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
private String dotStuffUsingByteBuf(String testString, boolean atStartOfLine, boolean appendCRLF) {
  ByteBuf sourceBuffer = ALLOCATOR.buffer();
  sourceBuffer.writeBytes(testString.getBytes(StandardCharsets.UTF_8));

  byte[] previousBytes = atStartOfLine ? null : new byte[] { 'x', 'y' };
  ByteBuf destBuffer = DotStuffing.createDotStuffedBuffer(ALLOCATOR, sourceBuffer, previousBytes,
      appendCRLF ? MessageTermination.ADD_CRLF : MessageTermination.DO_NOT_TERMINATE);

  byte[] bytes = new byte[destBuffer.readableBytes()];
  destBuffer.getBytes(0, bytes);
  return new String(bytes, CharsetUtil.UTF_8);
}
 
開發者ID:HubSpot,項目名稱:NioSmtpClient,代碼行數:13,代碼來源:DotStuffingTest.java

示例7: channelRead

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    Channel udpChannel = XChannelMapper.getUdpChannel(udpSource);
    if (udpChannel == null) {
        log.warn("Bad Connection! (udp channel closed)");
        XChannelMapper.closeChannelGracefullyByTcpChannel(ctx.channel());
    } else if (udpChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                bytes = wrapper.unwrap(bytes);
                XRequest request = requestResolver.parse(bytes);
                String host = request.getHost();
                int port = request.getPort();
                byte[] content = Arrays.copyOfRange(bytes, bytes.length - request.getSubsequentDataLength(), bytes.length);
                log.info("\t          Proxy << Target \tFrom   {}:{}", host, port);

                // redirect tcp -> udp
                udpChannel.writeAndFlush(new DatagramPacket(Unpooled.wrappedBuffer(content), udpSource, new InetSocketAddress(host, port)));
                log.info("\tClient << Proxy           \tGet [{} bytes]", content.length);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
開發者ID:ZhangJiupeng,項目名稱:AgentX,代碼行數:29,代碼來源:Tcp2UdpHandler.java

示例8: directBuffer

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
/**
 * Listing 5.2
 */
public static void directBuffer(ByteBuf directBuf) {
    if (!directBuf.hasArray()) {
        int length = directBuf.readableBytes();
        byte[] array = new byte[length];
        directBuf.getBytes(directBuf.readerIndex(), array);
        handleArray(array, 0, length);
    }

}
 
開發者ID:zy416548283,項目名稱:NettyStudy,代碼行數:13,代碼來源:ByteBufExamples.java

示例9: extractMultiMapping

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
private Map<RtTag, byte[]> extractMultiMapping(ByteBuf msg) {
  // extractOffsets will leave the reader index positioned at the first tag
  int[] offsets = extractOffsets(msg);

  int startOfValues = msg.readerIndex() + (4 * numTags);
  Map<RtTag, byte[]> mapping = new LinkedHashMap<>(numTags);
  RtTag prevTag = null;

  for (int i = 0; i < offsets.length; i++) {
    long uintCurrTag = msg.readUnsignedInt();
    RtTag currTag = RtTag.fromUnsignedInt((int) uintCurrTag);

    if ((prevTag != null) && currTag.isLessThan(prevTag)) {
      String exMsg = String.format(
          "tags not strictly increasing: current '%s' (0x%08x), previous '%s' (0x%08x)",
          currTag, currTag.valueLE(), prevTag, prevTag.valueLE()
      );
      throw new TagsNotIncreasingException(exMsg);
    }

    int valueIdx = startOfValues + offsets[i];
    int valueLen = ((i + 1) == offsets.length) ? msg.readableBytes() - offsets[i]
                                               : offsets[i + 1] - offsets[i];
    byte[] valueBytes = new byte[valueLen];
    msg.getBytes(valueIdx, valueBytes);

    mapping.put(currTag, valueBytes);
    prevTag = currTag;
  }

  return mapping;
}
 
開發者ID:int08h,項目名稱:nearenough,代碼行數:33,代碼來源:RtMessage.java

示例10: readContent

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
protected static byte[] readContent(FullHttpRequest request) {
    ByteBuf buf = request.content();
    if (buf == null) {
        return null;
    }
    byte[] bytes = new byte[buf.readableBytes()];
    buf.getBytes(buf.readerIndex(), bytes);
    return bytes;
}
 
開發者ID:xipki,項目名稱:xitk,代碼行數:10,代碼來源:AbstractHttpServlet.java

示例11: writeToStream

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
public void writeToStream(FSDataOutputStream stream) throws IOException {
  Stopwatch watch = Stopwatch.createStarted();
  ByteBuf buf = null;
  try {
    check = ThreadLocalRandom.current().nextLong();
    start = stream.getPos();
    logger.debug("Writing check value {} at position {}", check, start);
    stream.writeLong(check);
    batch.getHeader().writeDelimitedTo(stream);
    buf = batch.getBody();
    if (buf != null) {
      bodyLength = buf.capacity();
    } else {
      bodyLength = 0;
    }
    if (bodyLength > 0) {
      buf.getBytes(0, stream, bodyLength);
    }
    stream.hsync();
    FileStatus status = spillFile.getFileStatus();
    long len = status.getLen();
    logger.debug("After spooling batch, stream at position {}. File length {}", stream.getPos(), len);
    long t = watch.elapsed(TimeUnit.MICROSECONDS);
    logger.debug("Took {} us to spool {} to disk. Rate {} mb/s", t, bodyLength, bodyLength / t);
  } finally {
    // even if the try block throws an exception we still want to send an ACK and release the lock
    // the caller will add the exception to deferred attribute and it will be thrown when the poll() method is called
    try {
      batch.sendOk(); // this can also throw an exception
    } finally {
      state = BatchState.SPILLED;
      batch = null;
      if (buf != null) {
        buf.release();
      }
    }
  }
}
 
開發者ID:dremio,項目名稱:dremio-oss,代碼行數:39,代碼來源:SpoolingRawBatchBuffer.java

示例12: encode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
@Override
protected void encode(ChannelHandlerContext channelHandlerContext, OutboundMsg msg, ByteBuf out) throws Exception {


    byte type = msg.getType();
    byte opt = msg.getOpt();
    String msgStr = msg.getMsgStr();
    byte[] data = msg.getData();

    byte[] msgBytes = msgStr.getBytes(Charset.forName("utf-8"));

    // 文本消息長度
    int msgLength = msgBytes.length;
    // 二進製數據長度
    int dataLength = data == null ? 0 : data.length;

    // 總消息長度
    int allDataLength = msgLength + dataLength + OTHER_INFO_LENGTH;

    out.writeBytes(OutboundMsg.getHEADER());//輸出頭部標識
    out.writeInt(allDataLength);//其後所有的數據長度(字節)
    out.writeByte(type);//數據類型
    out.writeByte(opt);//操作類型
    out.writeInt(msgLength);//信息數據長度(字節)
    out.writeBytes(msgBytes);//信息字符串內容(已加密,字節)
    if (data != null) {
        out.writeBytes(data);//二進製數據
    }
    byte[] bytesToCheck = new byte[allDataLength - 1];
    out.getBytes(7, bytesToCheck);
    byte check = calculate(bytesToCheck);
    out.writeByte(check);//冗餘校驗值
}
 
開發者ID:wyp0596,項目名稱:elegant-springboot,代碼行數:34,代碼來源:MsgEncoder.java

示例13: decode

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
/**
 * 解碼
 * 
 * @param in
 * @return
 * @throws Exception
 */
public static LibraMessage decode(ByteBuf in) throws Exception {
	LibraMessage message = new LibraMessage();
	message.setHead(LibraHead.decode(in));
	short bodyLength = in.readShort();// 消息體的長度
	if (bodyLength != in.readableBytes()) {
		LibraLog.error("LibraMessage.decode is error! params:bodyLength:" + bodyLength + "\treadableLength:" + in.readableBytes());
		return null;
	}
	ByteBuf bodyByteBuf = in.readBytes(in.readableBytes());
	byte[] array;
	// 反序列化數據的起始點
	int offset;
	// 可讀的數據字節長度
	int readableLen = bodyByteBuf.readableBytes();
	// 分為包含數組數據和不包含數組數據兩種形式
	if (bodyByteBuf.hasArray()) {
		array = bodyByteBuf.array();
		offset = bodyByteBuf.arrayOffset() + bodyByteBuf.readerIndex();
	} else {
		array = new byte[readableLen];
		bodyByteBuf.getBytes(bodyByteBuf.readerIndex(), array, 0, readableLen);
		offset = 0;
	}
	// 反序列化
	message.setBody(decodeBody(message.getHead().getProtocolID(), array, offset, readableLen));
	return message;
}
 
開發者ID:inspingcc,項目名稱:LibraSock,代碼行數:35,代碼來源:LibraMessage.java

示例14: writeToStream

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
public void writeToStream(FSDataOutputStream stream) throws IOException {
  Stopwatch watch = new Stopwatch();
  watch.start();
  available = false;
  check = ThreadLocalRandom.current().nextLong();
  start = stream.getPos();
  logger.debug("Writing check value {} at position {}", check, start);
  stream.writeLong(check);
  batch.getHeader().writeDelimitedTo(stream);
  ByteBuf buf = batch.getBody();
  if (buf != null) {
    bodyLength = buf.capacity();
  } else {
    bodyLength = 0;
  }
  if (bodyLength > 0) {
    buf.getBytes(0, stream, bodyLength);
  }
  stream.hsync();
  FileStatus status = fs.getFileStatus(path);
  long len = status.getLen();
  logger.debug("After spooling batch, stream at position {}. File length {}", stream.getPos(), len);
  batch.sendOk();
  latch.countDown();
  long t = watch.elapsed(TimeUnit.MICROSECONDS);
  logger.debug("Took {} us to spool {} to disk. Rate {} mb/s", t, bodyLength, bodyLength / t);
  if (buf != null) {
    buf.release();
  }
}
 
開發者ID:skhalifa,項目名稱:QDrill,代碼行數:31,代碼來源:SpoolingRawBatchBuffer.java

示例15: extract

import io.netty.buffer.ByteBuf; //導入方法依賴的package包/類
private String extract(Object o) {
  assertThat(o).isInstanceOf(ByteBuf.class);

  ByteBuf buffer = (ByteBuf) o;

  byte[] bytes = new byte[buffer.readableBytes()];
  buffer.getBytes(0, bytes);
  return new String(bytes, CharsetUtil.UTF_8);
}
 
開發者ID:HubSpot,項目名稱:NioSmtpClient,代碼行數:10,代碼來源:ByteBufMessageContentTest.java


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