java 从 netty ByteBuf 获取字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38164891/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:11:15  来源:igfitidea点击:

Getting string from netty ByteBuf

javanettybytebuffer

提问by aries

How can I get the string from a netty ByteBuf? As of now I am able to get it character by character. Is there a way to get the string object directly?

如何从 netty 获取字符串ByteBuf?到目前为止,我可以逐个字符地获取它。有没有办法直接获取字符串对象?

// message is of type ByteBuf
for (int i = 0; i < message.capacity(); i++) {
    byte b = message.payload().getByte(i);
    System.out.print((char) b);
}

回答by mileippert

Use the provided method ByteBuf.toString(Charset) .

使用提供的方法ByteBuf.toString(Charset)

回答by xinnjie

use ByteBuf.readCharSequence()

利用 ByteBuf.readCharSequence()

example is here:

例子在这里:

// here we use utf-8 decoding, you can choose the charset you want
String s = ByteBuf.readCharSequence(length, Charset.forName("utf-8")).toString()

note that ByteBuf.readCharSequence()returns java.lang.CharSequence, use toString()to get Stringobejct

请注意,ByteBuf.readCharSequence()返回java.lang.CharSequence,用于toString()获取String对象

回答by cilki

Take a look at this

看看这个

From there you can use new String(byte[])or some Base64 solution (since it's binary data I'm assuming)

从那里你可以使用new String(byte[])或一些 Base64 解决方案(因为它是我假设的二进制数据)