Example usage for io.netty.buffer ByteBuf readerIndex

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

Introduction

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

Prototype

public abstract ByteBuf readerIndex(int readerIndex);

Source Link

Document

Sets the readerIndex of this buffer.

Usage

From source file:TestTCPServer.java

License:Open Source License

public static void main(String... args) throws Throwable {
    IOService service = new IOService();
    TCPAcceptor acceptor = new TCPAcceptor(service);
    acceptor.setOption(ChannelOption.SO_BACKLOG, 3);
    acceptor.setChildOption(ChannelOption.TCP_NODELAY, true);
    acceptor.setChildOption(ChannelOption.SO_KEEPALIVE, true);

    acceptor.bind(4321);/*from  www  .  ja  va  2  s. c om*/
    TCPSocket con = acceptor.accept();
    ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(16 * 1000);
    byte[] bytea = new byte[buffer.capacity()];
    long bytes;

    System.out.println("Connected " + con.remoteEndpoint());
    bytes = con.receive(buffer);
    while (bytes != -1 && buffer.getByte(0) != 4) {
        buffer.readBytes(bytea, 0, (int) bytes);
        System.out.print(new String(bytea, 0, (int) bytes));
        buffer.readerIndex(0).writerIndex(0);
        con.send(buffer, (int) bytes);
        buffer.readerIndex(0).writerIndex(0);
        bytes = con.receive(buffer);
    }

    System.out.println("Connection closed");
    con.close();

    acceptor.close();
    service.cancel();
}

From source file:alluxio.worker.block.UnderFileSystemBlockReader.java

License:Apache License

/**
 * This interface is supposed to be used for sequence block reads.
 *
 * @param buf the byte buffer//from   ww w .  ja  va  2  s .  c o m
 * @return the number of bytes read, -1 if it reaches EOF and none was read
 * @throws IOException if any I/O errors occur when reading the block
 */
@Override
public int transferTo(ByteBuf buf) throws IOException {
    Preconditions.checkState(!mClosed);
    if (mUnderFileSystemInputStream == null) {
        return -1;
    }
    if (mBlockMeta.getBlockSize() <= mInStreamPos) {
        return -1;
    }
    // Make a copy of the state to keep track of what we have read in this transferTo call.
    ByteBuf bufCopy = null;
    if (mBlockWriter != null) {
        bufCopy = buf.duplicate();
        bufCopy.readerIndex(bufCopy.writerIndex());
    }
    int bytesToRead = (int) Math.min((long) buf.writableBytes(), mBlockMeta.getBlockSize() - mInStreamPos);
    int bytesRead = buf.writeBytes(mUnderFileSystemInputStream, bytesToRead);

    if (bytesRead <= 0) {
        return bytesRead;
    }

    mInStreamPos += bytesRead;

    if (mBlockWriter != null) {
        bufCopy.writerIndex(buf.writerIndex());
        while (bufCopy.readableBytes() > 0) {
            mBlockWriter.transferFrom(bufCopy);
        }
    }

    return bytesRead;
}

From source file:com.corundumstudio.socketio.handler.PacketHandlerTest.java

License:Apache License

public void testDecodePerf() throws Exception {
    PacketListener listener = new PacketListener(null, null, null) {
        @Override// w w  w  .j ava 2  s  . c  om
        public void onPacket(Packet packet, NamespaceClient client) {
        }
    };
    PacketHandler handler = new PacketHandler(listener, decoder, namespacesHub);
    long start = System.currentTimeMillis();
    ByteBuf buffer = Unpooled.wrappedBuffer(
            "\ufffd10\ufffd3:::\ufffd7\ufffd3:::53d\ufffd3\ufffd0::\ufffd5\ufffd3:::5\ufffd7\ufffd3:::53d\ufffd3\ufffd0::\ufffd5\ufffd3:::5\ufffd7\ufffd3:::53d\ufffd3\ufffd0::\ufffd5\ufffd3:::5\ufffd7\ufffd3:::53d\ufffd3\ufffd0::\ufffd5\ufffd3:::5\ufffd7\ufffd3:::53d\ufffd3\ufffd0::"
                    .getBytes());
    for (int i = 0; i < 50000; i++) {
        handler.channelRead0(null, new PacketsMessage(client, buffer));
        buffer.readerIndex(0);
    }
    long end = System.currentTimeMillis() - start;
    System.out.println(end + "ms");
    // 670ms
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private void parseHeader(ByteBuf frame, Packet packet, PacketType innerType) {
    int endIndex = frame.bytesBefore((byte) '[');
    if (endIndex <= 0) {
        return;//  w ww.  j a  v  a2 s. c  o m
    }

    int attachmentsDividerIndex = frame.bytesBefore(endIndex, (byte) '-');
    boolean hasAttachments = attachmentsDividerIndex != -1;
    if (hasAttachments && PacketType.BINARY_EVENT.equals(innerType)) {
        int attachments = (int) readLong(frame, attachmentsDividerIndex);
        packet.initAttachments(attachments);
        frame.readerIndex(frame.readerIndex() + 1);

        endIndex -= attachmentsDividerIndex + 1;
    }
    if (endIndex == 0) {
        return;
    }

    // TODO optimize
    boolean hasNsp = frame.bytesBefore(endIndex, (byte) ',') != -1;
    if (hasNsp) {
        String nspAckId = readString(frame, endIndex);
        String[] parts = nspAckId.split(",");
        String nsp = parts[0];
        packet.setNsp(nsp);
        if (parts.length > 1) {
            String ackId = parts[1];
            packet.setAckId(Long.valueOf(ackId));
        }
    } else {
        long ackId = readLong(frame, endIndex);
        packet.setAckId(ackId);
    }
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private void parseBody(ClientHead head, ByteBuf frame, Packet packet) throws IOException {
    if (packet.getType() == PacketType.MESSAGE) {
        if (packet.getSubType() == PacketType.CONNECT || packet.getSubType() == PacketType.DISCONNECT) {
            packet.setNsp(readString(frame));
        }//from  w  w w  . j a v a 2s  .  c om

        if (packet.getSubType() == PacketType.ACK) {
            ByteBufInputStream in = new ByteBufInputStream(frame);
            AckCallback<?> callback = ackManager.getCallback(head.getSessionId(), packet.getAckId());
            AckArgs args = jsonSupport.readAckArgs(in, callback);
            packet.setData(args.getArgs());
        }

        if (packet.getSubType() == PacketType.EVENT || packet.getSubType() == PacketType.BINARY_EVENT) {
            if (packet.hasAttachments() && !packet.isAttachmentsLoaded()) {
                packet.setDataSource(Unpooled.copiedBuffer(frame));
                frame.readerIndex(frame.readableBytes());
                head.setLastBinaryPacket(packet);
            } else {
                ByteBufInputStream in = new ByteBufInputStream(frame);
                Event event = jsonSupport.readValue(packet.getNsp(), in, Event.class);
                packet.setName(event.getName());
                packet.setData(event.getArgs());
            }
        }
    }
}

From source file:com.datastax.driver.core.CBUtil.java

License:Apache License

public static byte[] readRawBytes(ByteBuf cb) {
    if (cb.hasArray() && cb.readableBytes() == cb.array().length) {
        // Move the readerIndex just so we consistently consume the input
        cb.readerIndex(cb.writerIndex());
        return cb.array();
    }//w w  w. ja  va2s.  c o  m

    // Otherwise, just read the bytes in a new array
    byte[] bytes = new byte[cb.readableBytes()];
    cb.readBytes(bytes);
    return bytes;
}

From source file:com.datastax.driver.core.LZ4Compressor.java

License:Apache License

private ByteBuf compressDirect(ByteBuf input) throws IOException {
    int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes());
    // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
    // LZ4Compressor.compress and so eliminate memory copies.
    ByteBuf output = input.alloc().directBuffer(INTEGER_BYTES + maxCompressedLength);
    try {/*from w ww  . j a va  2s .co m*/
        ByteBuffer in = inputNioBuffer(input);
        // Increase reader index.
        input.readerIndex(input.writerIndex());

        output.writeInt(in.remaining());

        ByteBuffer out = outputNioBuffer(output);
        int written = compressor.compress(in, in.position(), in.remaining(), out, out.position(),
                out.remaining());
        // Set the writer index so the amount of written bytes is reflected
        output.writerIndex(output.writerIndex() + written);
    } catch (Exception e) {
        // release output buffer so we not leak and rethrow exception.
        output.release();
        throw new IOException(e);
    }
    return output;
}

From source file:com.datastax.driver.core.LZ4Compressor.java

License:Apache License

private ByteBuf decompressDirect(ByteBuf input) throws IOException {
    // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
    // LZ4Compressor.decompress and so eliminate memory copies.
    int readable = input.readableBytes();
    int uncompressedLength = input.readInt();
    ByteBuffer in = inputNioBuffer(input);
    // Increase reader index.
    input.readerIndex(input.writerIndex());
    ByteBuf output = input.alloc().directBuffer(uncompressedLength);
    try {/*from w  w w  .  j  av a2  s  .  c o m*/
        ByteBuffer out = outputNioBuffer(output);
        int read = decompressor.decompress(in, in.position(), out, out.position(), out.remaining());
        if (read != readable - INTEGER_BYTES)
            throw new IOException("Compressed lengths mismatch");

        // Set the writer index so the amount of written bytes is reflected
        output.writerIndex(output.writerIndex() + uncompressedLength);
    } catch (Exception e) {
        // release output buffer so we not leak and rethrow exception.
        output.release();
        throw new IOException(e);
    }
    return output;
}

From source file:com.datastax.driver.core.SnappyCompressor.java

License:Apache License

private ByteBuf compressDirect(ByteBuf input) throws IOException {
    int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes());
    // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
    // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
    ByteBuf output = input.alloc().directBuffer(maxCompressedLength);
    try {/*from w ww  .  jav  a  2  s  . c o  m*/
        ByteBuffer in = inputNioBuffer(input);
        // Increase reader index.
        input.readerIndex(input.writerIndex());

        ByteBuffer out = outputNioBuffer(output);
        int written = Snappy.compress(in, out);
        // Set the writer index so the amount of written bytes is reflected
        output.writerIndex(output.writerIndex() + written);
    } catch (IOException e) {
        // release output buffer so we not leak and rethrow exception.
        output.release();
        throw e;
    }
    return output;
}

From source file:com.datastax.driver.core.SnappyCompressor.java

License:Apache License

private ByteBuf decompressDirect(ByteBuf input) throws IOException {
    ByteBuffer in = inputNioBuffer(input);
    // Increase reader index.
    input.readerIndex(input.writerIndex());

    if (!Snappy.isValidCompressedBuffer(in))
        throw new DriverInternalError("Provided frame does not appear to be Snappy compressed");

    // If the input is direct we will allocate a direct output buffer as well as this will allow us to use
    // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
    ByteBuf output = input.alloc().directBuffer(Snappy.uncompressedLength(in));
    try {/*from w w  w.  ja v  a2 s. co  m*/
        ByteBuffer out = outputNioBuffer(output);

        int size = Snappy.uncompress(in, out);
        // Set the writer index so the amount of written bytes is reflected
        output.writerIndex(output.writerIndex() + size);
    } catch (IOException e) {
        // release output buffer so we not leak and rethrow exception.
        output.release();
        throw e;
    }
    return output;
}