繁体   English   中英

如何将 a.netty ByteBuf 转换为 String,反之亦然

[英]How to convert a netty ByteBuf to a String and vice versa

有没有办法将 a.netty ByteBuf 转换为 String,反之亦然?

public String toString(ByteBuf b){

 //return b enconded to a String
}

public Bytebuf ToByteBuff(String s){

  //return s decoded to Bytebuf
}

您可以使用ByteBuf.toString(Charset)转换为字符串。

您可以使用Unpooled.wrappedBuffer(byte[]) String.getBytes(Charset)Unpooled.wrappedBuffer(byte[])转换为ByteBuf。

您可以使用Unpooled.copiedBuffer(String, Charset)从字符串创建ByteBuf

要将 ByteBuf 转换为 String,需要:

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

要将 String 转换为 ByteBuf,需要:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM