| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- package com.qlm.netty.codec;
- import com.qlm.netty.protocol.CustomProtocol;
- import io.netty.buffer.ByteBuf;
- import io.netty.channel.ChannelHandlerContext;
- import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
- public class CustomDecoder extends LengthFieldBasedFrameDecoder {
- // 长度字段的偏移量
- private static final int LENGTH_FIELD_OFFSET = 21; // deviceId(20字节) + type(1字节)
- // 长度字段的长度
- private static final int LENGTH_FIELD_LENGTH = 4;
- public CustomDecoder() {
- // maxFrameLength: 最大帧长度
- // lengthFieldOffset: 长度字段的偏移量
- // lengthFieldLength: 长度字段的长度
- // lengthAdjustment: 长度调整值
- // initialBytesToStrip: 跳过的初始字节数
- super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, 0, LENGTH_FIELD_OFFSET + LENGTH_FIELD_LENGTH);
- }
- @Override
- protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
- ByteBuf frame = (ByteBuf) super.decode(ctx, in);
- if (frame == null) {
- return null;
- }
- try {
- // 读取设备ID (20字节)
- byte[] deviceIdBytes = new byte[20];
- frame.readBytes(deviceIdBytes);
- String deviceId = new String(deviceIdBytes).trim();
- // 读取消息类型
- byte type = frame.readByte();
- // 读取消息长度
- int length = frame.readInt();
- // 读取消息内容
- byte[] content = new byte[length];
- frame.readBytes(content);
- return new CustomProtocol(deviceId, type, content);
- } finally {
- frame.release();
- }
- }
- }
|