DLT10376协议的netty decoder

发布时间:2026/7/7 17:46:48
DLT10376协议的netty decoder
应该有人会找这个吧谁用留个评论packagecom.wisdompoint.wpbuilder.io.zt.nettyserver.message;importcn.hutool.core.util.ArrayUtil;importcn.hutool.core.util.ByteUtil;importio.netty.buffer.ByteBuf;importio.netty.buffer.Unpooled;importio.netty.channel.ChannelHandlerContext;importio.netty.handler.codec.ByteToMessageDecoder;importorg.apache.commons.lang3.ArrayUtils;importjava.nio.ByteOrder;importjava.util.Arrays;importjava.util.List;publicclassDLT10376DecoderextendsByteToMessageDecoder{privatestaticfinalbyteHEADER0x68;privatestaticfinalbyteFOOTER0x16;/** * 起始字符 68H * 长度 3A01 * 长度 3A01 * 起始字符 68H * 控制域C * 地址域A * 链路用户数据 * 校验和CS * 结束字符 16H * * 长度 是控制域、地址域、链路用户数据之和 * */Overrideprotectedvoiddecode(ChannelHandlerContextchannelHandlerContext,ByteBufin,ListObjectout)throwsException{while(in.isReadable()){in.markReaderIndex();byteheaderBytein.readByte();if(headerByte!HEADER){continue;}byte[]headBytesnewbyte[5];in.readBytes(headBytes);byte[]L1ArrArrayUtils.subarray(headBytes,0,2);byte[]L2ArrArrayUtils.subarray(headBytes,2,4);bytesecondHeaderheadBytes[4];if(!Arrays.equals(L1Arr,L2Arr)||secondHeader!HEADER){continue;}// 小端序转 short (16位)shortlittleEndianValByteUtil.bytesToShort(L1Arr,ByteOrder.LITTLE_ENDIAN);// 右移2位intlength(littleEndianVal0xFFFF)2;// 78intreadableBytesin.readableBytes();if(readableByteslength2){in.resetReaderIndex();//可读数据不够 重置索引继续读取数据return;}byte[]restBytesnewbyte[length2];in.readBytes(restBytes);//判断最后一个if(restBytes[restBytes.length-1]!FOOTER){continue;}//组合整个报文帧byte[]framenewbyte[]{headerByte};frameArrayUtil.addAll(frame,headBytes,restBytes);booleanbvalidateFrame(frame);if(b){out.add(Unpooled.wrappedBuffer(frame));}}}/** * 计算报文帧的校验和 * param frame * return */booleanvalidateFrame(byte[]frame){if(frame[0]!HEADER){returnfalse;}intcsframe[frame.length-2]0xFF;intsum0;for(inti6;iframe.length-2;i){sum(sumframe[i])0xFF;}returncssum;}}