Getting string from netty ByteBuf

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-09 16:15:42

问题


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?

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

回答1:


Use the provided method ByteBuf.toString(Charset) .




回答2:


use 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 String obejct




回答3:


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)



来源:https://stackoverflow.com/questions/38164891/getting-string-from-netty-bytebuf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!