Kaleb Blue
Kaleb Blue

Reputation: 507

How to convert a netty ByteBuf to a String and vice versa

Is there a way to convert a netty ByteBuf to a String and vice versa?

public String toString(ByteBuf b){

 //return b enconded to a String
}

public Bytebuf ToByteBuff(String s){

  //return s decoded to Bytebuf
}

Upvotes: 13

Views: 14080

Answers (3)

Bằng Rikimaru
Bằng Rikimaru

Reputation: 1585

To convert ByteBuf to String, it needs:

 public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        String clientMessage = in.toString(CharsetUtil.UTF_8);

To convert String to ByteBuf, it needs:

 String message = "text";
 ByteBuf in = Unpooled.wrappedBuffer(message.getBytes());

Upvotes: 2

Stefan Birkner
Stefan Birkner

Reputation: 24510

You can create a ByteBuf from a String with Unpooled.copiedBuffer(String, Charset).

Upvotes: 4

Chris O'Toole
Chris O'Toole

Reputation: 1281

You can use ByteBuf.toString(Charset) to convert to string.

You can use String.getBytes(Charset) and Unpooled.wrappedBuffer(byte[]) to convert to ByteBuf.

Upvotes: 28

Related Questions