如何将Netty的ByteBuf转换为字符串,反之亦然?

13

有没有一种方法可以将Netty的ByteBuf转换为String,反之亦然?

public String toString(ByteBuf b){

 //return b enconded to a String
}

public Bytebuf ToByteBuff(String s){

  //return s decoded to Bytebuf
}
3个回答

26

1
这虽然很简单,但非常有帮助。太感谢了! - Jared Scarito

4

你可以使用Unpooled.copiedBuffer(String, Charset)方法从字符串中创建一个ByteBuf


2
将ByteBuf转换为字符串,需要以下步骤:
 public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        String clientMessage = in.toString(CharsetUtil.UTF_8);

将字符串转换为ByteBuf,需要以下步骤:
 String message = "text";
 ByteBuf in = Unpooled.wrappedBuffer(message.getBytes());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接