一般字节数组转字符串
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;
}
转换成十六进制的字符串数据(发送的也必须是十六进制的字节数组)
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf=(ByteBuf)msg;
try {
String string=ByteBufUtil.hexDump(buf).toUpperCase();
//System.out.println(string);
}
finally {
ReferenceCountUtil.release(msg);
}
}