[Update]自定义协议并解决TCP粘包/拆包问题

This commit is contained in:
chenfufeng
2022-02-14 15:58:48 +08:00
parent 4e2c6ffd7a
commit fc89d1a34b
10 changed files with 227 additions and 84 deletions

View File

@@ -0,0 +1,34 @@
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;
}
}