Example usage for io.netty.buffer ByteBuf capacity

List of usage examples for io.netty.buffer ByteBuf capacity

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf capacity.

Prototype

public abstract int capacity();

Source Link

Document

Returns the number of bytes (octets) this buffer can contain.

Usage

From source file:com.talent.balance.frontend.decode.FrontendRequestDecoder.java

License:Open Source License

@Override
public PacketWithMeta decode(ByteBuf buffer, ChannelContext channelContext) throws DecodeException {
    BalancePacket frontendRequestPacket = new BalancePacket();
    frontendRequestPacket.setBuffer(Unpooled.copiedBuffer(buffer));

    List<Packet> ret = new ArrayList<Packet>();
    ret.add(frontendRequestPacket);//from www. j  av a2 s .  co  m

    PacketWithMeta packetWithMeta = new PacketWithMeta();
    buffer.readerIndex(buffer.capacity());
    packetWithMeta.setPacketLenght(buffer.capacity());
    packetWithMeta.setPackets(ret);
    return packetWithMeta;
}

From source file:com.talent.mysql.packet.MysqlResponsePacket.java

License:Open Source License

public PacketWithMeta<Packet> decode(ByteBuf byteBuf) throws DecodeException {
    int capacity = byteBuf.capacity();
    PacketWithMeta<Packet> packetWithMeta = null;
    while (true) {
        if ((capacity - byteBuf.readerIndex()) < MysqlHeader.HEADER_LEN) //?
        {//from ww w.  j  a va 2s . co m
            if (packetWithMeta != null) {
                packetWithMeta.setPacketLenght(byteBuf.readerIndex());
            }

            return packetWithMeta;
        }

        if (byteBuf.order() == ByteOrder.BIG_ENDIAN) {
            byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);
        }

        MysqlHeader header = MysqlHeaderFactory.borrow();
        header.decode(byteBuf);

        ParseUtils.processReadIndex(byteBuf);

        //?
        if (capacity - byteBuf.readerIndex() < header.getBodyLength()) //?
        {
            if (packetWithMeta != null) {
                packetWithMeta.setPacketLenght(byteBuf.readerIndex());
            }
            return packetWithMeta;
        } else {
            T t = decodeBody(byteBuf, header);
            if (packetWithMeta == null) {
                packetWithMeta = new PacketWithMeta<Packet>();

                List<Packet> packets = new ArrayList<Packet>();
                packets.add(t);

                packetWithMeta.setPackets(packets);
                packetWithMeta.setPacketLenght(byteBuf.readerIndex());
                return packetWithMeta;

                //               com.talent.mysql.packet.factory.MysqlHeaderFactory.returnObj(t.getMysqlHeader());
            } else {
                packetWithMeta.getPackets().add(t);
            }
        }
    }

}

From source file:com.talent.nio.communicate.receive.TcpListener.java

License:Open Source License

/**
 * ??/* w  w w .j  ava 2s.  c  o  m*/
 * 
 * @param key
 * @return
 */
public void read(SelectionKey key) {
    SocketChannel sc = (SocketChannel) key.channel();
    ChannelContext channelContext = mapOfSocketChannelAndChannelContext.get(sc);

    if (channelContext == null) {
        log.error("channelContext is null");
        try {
            sc.close();
            this.selector.wakeup();
        } catch (IOException ioe) {
            log.error("channelContext is null,IOException occured when close the SocketChannel", ioe);
        }
        return;
    }

    try {
        ByteBuf datas = ChannelReader.read(sc, channelContext);// (key);
        if (datas != null && datas.capacity() > 0) {
            submitMsg(datas, channelContext);
        }
    } catch (IOException e) {
        channelContext.getReadIOErrorHandler().handle(sc, e, channelContext, null);
        return;
    }
}

From source file:com.talent.nio.utils.ByteUtils.java

License:Open Source License

/**
 * /*from   www .j  a va  2 s .c  om*/
 * @param buffer
 * @return
 * @throws IOException
 */
public static List<String> toLinesList(ByteBuf buffer) throws IOException {
    List<String> retList = new ArrayList<String>(20);

    int lastPosition = 0;
    int byteCountInOneLine = 0; // 

    byte lastByte = 0; // 
    int length = buffer.capacity();
    for (int i = 0; i < length; i++) {
        byte b = buffer.getByte(i);// .get();
        boolean isLastByte = (length - 1 == i); // ??
        byteCountInOneLine++;

        if (b == '\n') {
            if ((i > 0 && lastByte == '\r')) {
                if (byteCountInOneLine == 2) // ?????
                {
                    retList.add("\r\n"); // 
                } else {
                    byte[] bs1 = new byte[byteCountInOneLine];
                    buffer.getBytes(lastPosition, bs1);
                    String line1 = new String(bs1, "utf-8");
                    retList.add(line1);
                }
            } else {
                if (byteCountInOneLine == 1) // ?????
                {
                    retList.add("\n"); // 
                } else {
                    byte[] bs1 = new byte[byteCountInOneLine];
                    buffer.getBytes(lastPosition, bs1);
                    String line1 = new String(bs1, "utf-8");
                    retList.add(line1);
                }
            }

            byteCountInOneLine = 0;
            lastPosition = i + 1;
        } else if (isLastByte) {
            byte[] bs1 = new byte[byteCountInOneLine];
            buffer.getBytes(lastPosition, bs1);
            String line1 = new String(bs1, "utf-8");
            retList.add(line1);
        }

        lastByte = b;
    }
    return retList;
}

From source file:com.trinity.engine.protocol.MessageLookupService.java

License:Apache License

/**
 * Encodes a message into a stream//from ww w .  j  av  a2s  .c  o m
 *
 * @param message the message to encode to the buffer
 * @return a wrapped buffer that contains the header and the body of the message
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public <T extends Message> ByteBuf encode(T message) throws IOException {
    final MessageCodec<Message> codec = (MessageCodec<Message>) getCodec(message.getClass());
    if (codec == null) {
        throw new IOException("Unknown operation class: " + message.getClass());
    }
    final ByteBuf body = codec.encode(message);
    final ByteBuf header = Unpooled.buffer(3).writeByte(codec.getOpcode()).writeShort(body.capacity());
    return Unpooled.wrappedBuffer(header, body);
}

From source file:com.vethrfolnir.game.network.mu.crypt.MuCryptUtils.java

License:Open Source License

public static final short[] getAsUByteArray(ByteBuf buff) {
    short[] uByteArray = new short[buff.capacity()];
    for (int i = 0; i < uByteArray.length; i++) {
        uByteArray[i] = buff.getUnsignedByte(i);
    }//from   w  ww . j  a va 2 s.  c o  m
    return uByteArray;
}

From source file:com.vethrfolnir.game.network.mu.crypt.MuDecoder.java

License:Open Source License

private static int DecodeBlock(ByteBuf buff, ByteBuf outBuff, int offset, int size) {
    // decripted size
    int index = 0;

    if ((size % 11) != 0) {
        log.warn("Cannot decrypt packet, it's already decrypted!: Size " + size + " = " + ((size % 11)));
        log.warn(PrintData.printData(buff.nioBuffer()));
        return -1;
    }//from  w  w  w. j  a va  2s.co  m

    ByteBuf encrypted = alloc.heapBuffer(11, 11).order(ByteOrder.LITTLE_ENDIAN);
    short[] uByteArray = new short[encrypted.capacity()];

    ByteBuf decrypted = alloc.heapBuffer(8, 8).order(ByteOrder.LITTLE_ENDIAN);
    ByteBuf converter = alloc.heapBuffer(4).order(ByteOrder.LITTLE_ENDIAN);

    for (int i = 0; i < size; i += 11) {
        buff.readBytes(encrypted);

        //System.out.println("ENC: "+PrintData.printData(encrypted.nioBuffer()));
        int Result = BlockDecode(decrypted, getAsUByteArray(encrypted, uByteArray), converter,
                MuKeyFactory.getClientToServerPacketDecKeys());
        if (Result != -1) {
            //Buffer.BlockCopy(Decrypted, 0, m_DecryptResult, (OffSet - 1) + DecSize, Result);

            outBuff.writerIndex((offset - 1) + index);
            outBuff.writeBytes(decrypted);

            //outBuff.writeBytes(decrypted);

            decrypted.clear();
            encrypted.clear();
            converter.clear();
            //System.arraycopy(Decrypted, 0, m_DecryptResult, (OffSet - 1) + DecSize, Result);

            index += Result;
        }
    }

    return index;
}

From source file:com.whirvis.jraknet.client.RakNetClient.java

License:Open Source License

/**
 * Sends a Netty message over the channel raw.
 * <p>/*www . jav a2  s.  com*/
 * This should be used sparingly, as if it is used incorrectly it could
 * break server peers entirely. In order to send a message to a peer, use
 * one of the
 * {@link com.whirvis.jraknet.peer.RakNetPeer#sendMessage(Reliability, ByteBuf)
 * sendMessage()} methods.
 * 
 * @param buf
 *            the buffer to send.
 * @param address
 *            the address to send the buffer to.
 * @throws NullPointerException
 *             if the <code>buf</code>, <code>address</code>, or IP address
 *             of <code>address</code> are <code>null</code>.
 */
public final void sendNettyMessage(ByteBuf buf, InetSocketAddress address) throws NullPointerException {
    if (buf == null) {
        throw new NullPointerException("Buffer cannot be null");
    } else if (address == null) {
        throw new NullPointerException("Address cannot be null");
    } else if (address.getAddress() == null) {
        throw new NullPointerException("IP address cannot be null");
    }
    channel.writeAndFlush(new DatagramPacket(buf, address));
    log.debug("Sent netty message with size of " + buf.capacity() + " bytes (" + (buf.capacity() * 8)
            + " bits) to " + address);
}

From source file:com.whirvis.jraknet.peer.RakNetPeer.java

License:Open Source License

/**
 * Sends a message over the channel raw.
 * <p>// ww w.ja v  a  2  s .  c  o m
 * This will automatically update the <code>lastPacketSendTime</code> and
 * <code>packetsSentThisSecond</code> variable.
 * 
 * @param buf
 *            the buffer.
 * @throws NullPointerException
 *             if the <code>buf</code> is <code>null</code>.
 */
public final void sendNettyMessage(ByteBuf buf) throws NullPointerException {
    if (buf == null) {
        throw new NullPointerException("Buffer cannot be null");
    }
    channel.writeAndFlush(new DatagramPacket(buf, address));
    long currentTime = System.currentTimeMillis();
    if (currentTime - lastPacketsSentThisSecondResetTime >= 1000L) {
        this.packetsSentThisSecond = 0;
        this.lastPacketsSentThisSecondResetTime = currentTime;
    }
    this.lastPacketSendTime = currentTime;
    this.packetsSentThisSecond++;
    log.debug("Sent netty message with size of " + buf.capacity() + " bytes (" + (buf.capacity() * 8)
            + " bits) to " + address);
}

From source file:com.yahoo.pulsar.common.api.DoubleByteBuf.java

License:Apache License

@Override
public DoubleByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) {
    checkDstIndex(index, length, dstIndex, dst.capacity());
    if (length == 0) {
        return this;
    }/*from  w  w w.j  a v  a2s . co m*/

    int b1Length = Math.min(length, b1.readableBytes() - index);
    if (b1Length > 0) {
        b1.getBytes(b1.readerIndex() + index, dst, dstIndex, b1Length);
        dstIndex += b1Length;
        length -= b1Length;
        index = 0;
    } else {
        index -= b1.readableBytes();
    }

    if (length > 0) {
        int b2Length = Math.min(length, b2.readableBytes() - index);
        b2.getBytes(b2.readerIndex() + index, dst, dstIndex, b2Length);
    }
    return this;
}