Netty_ByteBuf代码示例

Netty_ByteBuf代码示例

@Test
public void test99() {
    String msg = "sasdfasdfasdfasdfasdf";
    ByteBuf buf = Unpooled.copiedBuffer(msg.getBytes());

    System.out.println("readerIndex=" + buf.readerIndex());
    System.out.println("writerIndex=" + buf.writerIndex());

    String msg2 = "hello world!";
    if (buf.isWritable()) {
        buf.writeBytes(msg2.getBytes());
    }

    System.out.println("readerIndex=" + buf.readerIndex());
    System.out.println("writerIndex=" + buf.writerIndex());

    int initialCapacity = 300;
    ByteBuf buf1 = Unpooled.buffer(initialCapacity);

    String hello = "how i need you!";
    String hello2 = "how i miss you!";

    if (buf1.isWritable()) {
        buf1.writeBytes(hello.getBytes());
    }

    if (buf1.isWritable()) {
        buf1.writeBytes(hello2.getBytes());
    }

    System.out.println("readerIndex=" + buf1.readerIndex());
    System.out.println("writerIndex=" + buf1.writerIndex());

    System.out.println("read buf1....");

    byte[] dest = new byte[15];
    buf1.readBytes(dest);
    System.out.println(new String(dest));

    System.out.println("readerIndex=" + buf1.readerIndex());
    System.out.println("writerIndex=" + buf1.writerIndex());

    System.out.println("discard read bytes...");
    buf1.discardReadBytes();
    System.out.println("readerIndex=" + buf1.readerIndex());
    System.out.println("writerIndex=" + buf1.writerIndex());


    System.out.println("buf2 test....");
    ByteBuf buf2 = Unpooled.buffer();
    buf2.setInt(3, 12);
    System.out.println(buf2.getInt(3)); //12

    System.out.println("readerIndex=" + buf2.readerIndex());
    System.out.println("writerIndex=" + buf2.writerIndex());

    buf2.setByte(5, 12);
    System.out.println(buf2.getByte(5)); //12

    System.out.println("readerIndex=" + buf2.readerIndex()); //0
    System.out.println("writerIndex=" + buf2.writerIndex()); //0

    buf2.writeInt(18);
    System.out.println(buf2.readInt()); //12

    System.out.println("readerIndex=" + buf2.readerIndex());  //4
    System.out.println("writerIndex=" + buf2.writerIndex());  //4
    System.out.println("Capacity=" + buf2.capacity()); //256
}

结果:

readerIndex=0

writerIndex=21

readerIndex=0

writerIndex=21

readerIndex=0

writerIndex=30

read buf1....

how i need you!

readerIndex=15

writerIndex=30

discard read bytes...

readerIndex=0

writerIndex=15

buf2 test....

12

readerIndex=0

writerIndex=0

12

readerIndex=0

writerIndex=0

18

readerIndex=4

writerIndex=4

Capacity=256


Process finished with exit code 0


上文讲解:http://my.oschina.net/xinxingegeya/blog/285063

=============================END=============================


你可能感兴趣的:(Netty_ByteBuf代码示例)