CustomDecoder.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.qlm.netty.codec;
  2. import com.qlm.netty.protocol.CustomProtocol;
  3. import io.netty.buffer.ByteBuf;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
  6. public class CustomDecoder extends LengthFieldBasedFrameDecoder {
  7. // 长度字段的偏移量
  8. private static final int LENGTH_FIELD_OFFSET = 21; // deviceId(20字节) + type(1字节)
  9. // 长度字段的长度
  10. private static final int LENGTH_FIELD_LENGTH = 4;
  11. public CustomDecoder() {
  12. // maxFrameLength: 最大帧长度
  13. // lengthFieldOffset: 长度字段的偏移量
  14. // lengthFieldLength: 长度字段的长度
  15. // lengthAdjustment: 长度调整值
  16. // initialBytesToStrip: 跳过的初始字节数
  17. super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, 0, LENGTH_FIELD_OFFSET + LENGTH_FIELD_LENGTH);
  18. }
  19. @Override
  20. protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
  21. ByteBuf frame = (ByteBuf) super.decode(ctx, in);
  22. if (frame == null) {
  23. return null;
  24. }
  25. try {
  26. // 读取设备ID (20字节)
  27. byte[] deviceIdBytes = new byte[20];
  28. frame.readBytes(deviceIdBytes);
  29. String deviceId = new String(deviceIdBytes).trim();
  30. // 读取消息类型
  31. byte type = frame.readByte();
  32. // 读取消息长度
  33. int length = frame.readInt();
  34. // 读取消息内容
  35. byte[] content = new byte[length];
  36. frame.readBytes(content);
  37. return new CustomProtocol(deviceId, type, content);
  38. } finally {
  39. frame.release();
  40. }
  41. }
  42. }