Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting string from netty ByteBuf

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);
}
like image 540
aries Avatar asked Jul 02 '16 22:07

aries


2 Answers

Use the provided method ByteBuf.toString(Charset) .

like image 106
mileippert Avatar answered Oct 31 '22 14:10

mileippert


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

like image 4
xinnjie Avatar answered Oct 31 '22 12:10

xinnjie