CompositeByteBuf 的 readableBytes 返回 0 [英] CompositeByteBuf has readableBytes return 0

查看:206
本文介绍了CompositeByteBuf 的 readableBytes 返回 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码有什么问题?它总是为 readableBytes 打印 0,即使 CompositeByteBuf 中有明确的数据.

What's the issue with following code? It always prints 0 for readableBytes, even though there is clearly data in CompositeByteBuf.

    private void compositeTest() {
       ByteBuf buf1 = Unpooled.buffer(1024);
       buf1.writeBytes("hello".getBytes(StandardCharsets.UTF_8));
       ByteBuf buf2 = Unpooled.buffer(1024);
       buf2.writeBytes("world".getBytes(StandardCharsets.UTF_8));

       CompositeByteBuf composite = Unpooled.compositeBuffer();
       composite.addComponent(buf1);
       composite.addComponent(buf2);

       System.out.println("Number of components " + composite.numComponents() +
                          ", Composite readable bytes: " +
                          composite.readableBytes()); 

       }

最后一个打印语句打印:

The last print statement prints:

组件数2,复合可读字节数:0

我在 pom.xml 中使用这个:

I'm using this in pom.xml:

    <dependency>
        <groupId>io.netty</groupId>
        <artifactId>netty-all</artifactId>
        <version>4.0.34.Final</version>
    </dependency>

是什么?

推荐答案

readableBytes() 计算为缓冲区 writerIndex - readerIndex.如果你调用 composite.writerIndex() 你会注意到它也返回 0.

readableBytes() is calculated as the buffers writerIndex - readerIndex. If you call composite.writerIndex() you'll notice that it also returns 0.

查看 addComponent() 的文档:

http:///netty.io/4.0/api/io/netty/buffer/CompositeByteBuf.html#addComponent(io.netty.buffer.ByteBuf)

请注意,此方法不会增加 CompositeByteBuf 的 writerIndex.如果你需要增加它,你需要自己处理.

为了使其正常工作,您可以手动设置writerIndex().

To make it work correctly you can manually set the writerIndex().

composite.writerIndex(buf1.writerIndex() + buf2.writerIndex())

您可能想要使用 Unpooled.wrappedBuffer() 来为您完成这项工作.

You might want to use Unpooled.wrappedBuffer() which will do this for you.

这篇关于CompositeByteBuf 的 readableBytes 返回 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆