1.数据准备及代码
ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer();//声明一个bytebuf 对象 byteBuf.writeByte(1);//第一位置存放数字1(占用1个字节) byteBuf.writeShort(0);//第二位置存放数字 0(占用2个字节) ,这里是打算做长度 String temp = "我是谁";//需要获取的数据 byteBuf.writeBytes(temp.getBytes());//获取字节数组 byteBuf.setShort(1,byteBuf.readableBytes());//设置第二位置的长度,也就是整个byteBuf对象的长度 get(byteBuf);//get方法解析
方法:
public static void get(ByteBuf in){ int inv = in.readerIndex(); int first =in.getByte(inv); inv++; int length = in.getShort(inv); inv+=2; // 减3 是因为前面是获取到总长度,前面占用了byte + short = 1+2=3 byte[] data = new byte[length - 3];//数据大小 in.getBytes(inv, data); try { String str = new String(data, 0, data.length, "utf-8"); System.out.println(str); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } }