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

The following are Jave code examples for showing how to use capacity() 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: jsf-sdk   File: CodecUtils.java   Source Code and License Vote up 6 votes
/**
 * encode报文头
 *
 * @param header
 *         MessageHeader
 * @param byteBuf
 *         报文
 * @see JSFProtocol
 */
public static short encodeHeader(MessageHeader header, ByteBuf byteBuf) {
    short headLength = 8; // 没有map 长度是8
    if( byteBuf.capacity() < 8 ) byteBuf.capacity(8);
    int writeIndex = byteBuf.writerIndex();
    byteBuf.writeShort(headLength);
    byteBuf.writeByte(header.getProtocolType());
    byteBuf.writeByte(header.getCodecType());
    byteBuf.writeByte(header.getMsgType());
    byteBuf.writeByte(header.getCompressType());
    byteBuf.writeInt(header.getMsgId());
    if (header.getAttrMapSize() > 0) {
        headLength += map2bytes(header.getAttrMap(), byteBuf);
        byteBuf.setBytes(writeIndex, short2bytes(headLength)); // 替换head长度的两位
    }
    return headLength;
}
 
Example 2
Project: SurvivalMMO   File: PacketDecoder.java   Source Code and License Vote up 6 votes
@Override
protected void decode(ChannelHandlerContext ctx, WebSocketFrame frame, List<Object> out) throws Exception {
    ByteBuf buf = frame.content().order(ByteOrder.LITTLE_ENDIAN);
    if (buf.capacity() < 1) {
        // Discard empty messages
        return;
    }

    buf.resetReaderIndex();
    int packetId = buf.readUnsignedByte();
    Packet packet = reg.SERVERBOUND.constructPacket(packetId);

    if (packet == null) {
        throw new UnknownPacketException("Unknown packet ID: " + packetId);
    }

    Server.log.finest("Received packet ID " + packetId + " (" + packet.getClass().getSimpleName() + ") from " + ctx.channel().remoteAddress());

    packet.readData(buf);
    out.add(packet);
}
 
Example 3
Project: sctalk   File: PduAttachData.java   Source Code and License Vote up 6 votes
public PduAttachData(ByteString bytes) {
    
    buffer.writeBytes(bytes.toByteArray());
    
    this.type = buffer.readInt();
    this.handle = buffer.readLong();
    this.serviceType = buffer.readInt();
    this.pduLength = buffer.readInt();
    ByteBuf buf = buffer.readBytes(this.pduLength);
    
    if (buf.hasArray()) {
        this.pdu = ByteString.copyFrom(buf.array());
    } else {
        byte[] content = new byte[buf.capacity()];
        buf.readBytes(content);
        this.pdu = ByteString.copyFrom(content);
    }
}
 
Example 4
Project: QDrill   File: SpoolingRawBatchBuffer.java   Source Code and License Vote up 5 votes
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();
  }
}
 
Example 5
Project: QDrill   File: DirectCodecFactory.java   Source Code and License Vote up 5 votes
public ByteBufBytesInput(ByteBuf buf, int offset, int length) {
  super();
  if(buf.capacity() == length && offset == 0){
    this.buf = buf;
  }else{
    this.buf = buf.slice(offset, length);
  }

  this.length = length;
}
 
Example 6
Project: NettyStudy   File: ByteBufExamples.java   Source Code and License Vote up 5 votes
/**
 * Listing 5.6
 */
public static void byteBufRelativeAccess(ByteBuf buffer) {
    for (int i = 0; i < buffer.capacity(); i++) {
        byte b = buffer.getByte(i);
        System.out.println((char) b);
    }

}
 
Example 7
Project: jsf-sdk   File: JSFEncoder.java   Source Code and License Vote up 5 votes
/**
 * 复制数据
 *
 * @param data
 *         序列化后的数据
 * @param out
 *         回传的数据
 * @see JSFProtocol
 */
private void write(ByteBuf data, ByteBuf out) {
    int totalLength = 2 + 4 + data.readableBytes();
    if(out.capacity() < totalLength) out.capacity(totalLength);
    out.writeBytes(Constants.MAGICCODEBYTE); // 写入magiccode
    int length = totalLength - 2 ; //  data.readableBytes() + 4  (4指的是FULLLENGTH)
    out.writeInt(length);   //4 for Length Field
    out.writeBytes(data, data.readerIndex(), data.readableBytes());
    //logger.trace("out length:{}",out.readableBytes());
}
 
Example 8
Project: WebSandboxMC   File: WebSocketFrameHandler.java   Source Code and License Vote up 5 votes
@Override
public void channelRead0(final ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
    webSocketServerThread.log(Level.FINEST, "channel read, frame="+frame);
    // TODO: log at INFO level if this the first data we received from a client (new first connection), to
    // help detect clients connecting but not sending authentication commands (in newPlayer)

    if (this.checkIPBans) {
        String ip = webSocketServerThread.getRemoteIP(ctx.channel());
        if (this.ipBans.contains(ip)) {
            webSocketServerThread.sendLine(ctx.channel(), "T,Banned from server"); // TODO: show reason, getBanList
            return;
        }
    }

    if (frame instanceof BinaryWebSocketFrame) {
        ByteBuf content = frame.content();

        byte[] bytes = new byte[content.capacity()];
        content.getBytes(0, bytes);

        final String string = new String(bytes);
        webSocketServerThread.log(Level.FINEST, "received "+content.capacity()+" bytes: "+string);

        this.webSocketServerThread.scheduleSyncTask(new Runnable() {
            @Override
            public void run() {
                webSocketServerThread.handle(string, ctx);
            }
        });
    } else {
        String message = "unsupported frame type: " + frame.getClass().getName();
        throw new UnsupportedOperationException(message);
    }
}
 
Example 9
Project: dremio-oss   File: SpoolingRawBatchBuffer.java   Source Code and License Vote up 5 votes
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();
      }
    }
  }
}
 
Example 10
Project: QDrill   File: DirectCodecFactory.java   Source Code and License Vote up 4 votes
public ByteBufBytesInput(ByteBuf buf) {
  this(buf, 0, buf.capacity());
}
 
Example 11
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.");
    }
}
 
Example 12
Project: pumpkindb-java   File: Closure.java   Source Code and License Vote up 3 votes
@Override public void encode(ByteBuf buffer) {
    ByteBuf buf = Unpooled.buffer();
    encodables.forEach(encodable -> encodable.encode(buf));

    int index = buf.writerIndex();

    buf.capacity(index);

    new Data(buf.array()).encode(buffer);
}