package net.xdclass.util;import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;import io.netty.buffer.ByteBuf;import io.netty.buffer.Unpooled;import io.netty.channel.ChannelHandlerContext;import io.netty.util.CharsetUtil;import net.xdclass.config.FrameConfig;import java.util.Arrays;import java.util.List;public class Test { public static void testdecode(ByteBuf in) throws Exception { System.out.println("进入编码器"); while (true) { System.out.println("一开始得长度" + in.readableBytes()); if (in.readableBytes() == 0) { break; } int begin_index = in.readerIndex(); //记录一开始得读标识 in.markReaderIndex();//最开始得地方 byte a = in.readByte(); byte[] markbyte = new byte[19]; //读到&=开始校验,只有读到头部才会进行校验 if (a == 36) { System.out.println("读到$符号,进行头尾部验证"); //先看看长度满不满足要求 if (in.readableBytes() < 19) { System.out.println("【半包】长度不够,复原至此次原始buf头部,等待后部接收"); in.resetReaderIndex(); break; } else { //满足了则看看这个$是否是头部 markbyte[0] = a; markbyte[1] = in.readByte(); for (int i = 0; i < 17; i++) { markbyte[i + 2] = in.readByte(); } if (isHeadOrTail(markbyte).equals("head")) { System.out.println("返回得in" + in.readableBytes()); System.out.println("检测到头部标识"); //此处进行msg读取 byte[] msg = new byte[100]; int index = 0; int msg_length=0; while (true) { byte b = in.readByte(); //看看是不是$符号 if (b == 36) { System.out.println("检测到第二个符号"); byte[] tail = new byte[17]; tail[0]=b; for (int i = 1; i < 17; i++) { tail[i] = in.readByte(); } if (isHeadOrTail(tail).equals("tail")){ System.out.println("尾部标识"); } break; } msg[index] = b; msg_length++; index++; } System.out.println(Arrays.toString(msg)); } else { System.out.println("不是头部标识,"); in.resetReaderIndex(); //不是头部,因为长度满足且不是头部则这个$符号肯定不是头部。复原至$后面一个字节等待后续读 //前面得逻辑正确得话,大概率是误码了 } } } } } public static String isHeadOrTail(byte[] markbyte) {// System.out.println("判断方法里得in" + in.readableBytes()); System.out.println(Arrays.toString(markbyte)); boolean head = true; boolean tail = true; if (!Arrays.equals(markbyte, FrameConfig.head_strb)) { head = false; } if (!Arrays.equals(markbyte, FrameConfig.tail_strb)) { tail = false; } if (head) { return "head"; } else if (tail) { return "tail"; } else { return "no"; } } public static void main(String[] args) throws Exception { ByteBuf byteBuf = Unpooled.copiedBuffer("$===+++start+++===$\" + msg + \"$===+++end+++===$", CharsetUtil.UTF_8); ByteBuf byteBuf2 = Unpooled.copiedBuffer("$===+++start+++===$", CharsetUtil.UTF_8);// System.out.println(byteBuf2.readableBytes()); String tail = "$===+++end+++===$"; System.out.println(Arrays.toString(tail.getBytes())); System.out.println(Arrays.toString("$===+++start+++===$\" + msg + \"$===+++end+++===$".getBytes())); System.out.println(Arrays.toString(FrameConfig.head_strb)); testdecode(byteBuf); }}