Netty ByteBuf 和 String 转换

参考https://blog.csdn.net/o1101574955/article/details/81024102

参考http://youyu4.iteye.com/blog/2361959

 Netty中的消息传递,都必须以字节的形式,以ChannelBuffer为载体传递。

public String convertByteBufToString(ByteBuf buf) {
String str;
if(buf.hasArray()) { // 处理堆缓冲区
str = new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
} else { // 处理直接缓冲区以及复合缓冲区
byte[] bytes = new byte[buf.readableBytes()];
buf.getBytes(buf.readerIndex(), bytes);
str = new String(bytes, 0, buf.readableBytes());
}
return str;
}
当需要通过ChannelHandlerContext发送String数据时,可以

ByteBuf in;
in.writeBytes("你收到了吗".getBytes());
posted @ 2018-11-01 13:46  北回归线的喵  阅读(8674)  评论(0编辑  收藏  举报