参考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());