package com.mogo.telematic; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; public class MogoLengthFrameDecoder extends LengthFieldBasedFrameDecoder { public static final int MAX_FRAME_LENGTH = 3 * 1024 * 1024; // 参考MogoProtocolMsg结构(https://blog.csdn.net/thinking_fioa/article/details/80573483) public static final int LENGTH_FIELD_OFFSET = 4; public static final int LENGTH_FIELD_SIZE = 4; public MogoLengthFrameDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) { super(maxFrameLength, lengthFieldOffset, lengthFieldLength); } @Override protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { ByteBuf byteBuf = (ByteBuf) super.decode(ctx, in); if (byteBuf == null) return null; MogoProtocolMsg mogoProtocolMsg = new MogoProtocolMsg(); mogoProtocolMsg.setProtocolType(byteBuf.readInt()); int length = byteBuf.readInt(); mogoProtocolMsg.setBodyLength(length); if (length > 0) { byte[] body = new byte[length]; byteBuf.readBytes(body); mogoProtocolMsg.setBody(body); } in.release(); return mogoProtocolMsg; } }