说明

和原始适配器相比,用户自定义适配器(CustomDataHandlingAdapter)简单很多。因为他只需要考虑接下来如何处理即可。

运行逻辑

3、用户自定义适配器 - 图1

还是以下列数据为例:
image.png

实现

  1. internal class MyCustomDataHandlingAdapter : CustomDataHandlingAdapter<MyRequestInfo>
  2. {
  3. /// <summary>
  4. /// 筛选解析数据。实例化的TRequest会一直保存,直至解析成功,或手动清除。
  5. /// <para>当不满足解析条件时,请返回<see cref="FilterResult.Cache"/>,此时会保存<see cref="ByteBlock.CanReadLen"/>的数据</para>
  6. /// <para>当数据部分异常时,请移动<see cref="ByteBlock.Pos"/>到指定位置,然后返回<see cref="FilterResult.GoOn"/></para>
  7. /// <para>当完全满足解析条件时,请返回<see cref="FilterResult.Success"/>最后将<see cref="ByteBlock.Pos"/>移至指定位置。</para>
  8. /// </summary>
  9. /// <param name="byteBlock">字节块</param>
  10. /// <param name="beCached">是否为上次遗留对象,当该参数为True时,request也将是上次实例化的对象。</param>
  11. /// <param name="request">对象。</param>
  12. /// <returns></returns>
  13. protected override FilterResult Filter(ByteBlock byteBlock, bool beCached, ref MyRequestInfo request, ref int tempCapacity)
  14. {
  15. //以下解析思路为一次性解析,不考虑缓存的临时对象。
  16. if (byteBlock.CanReadLen < 3)
  17. {
  18. return FilterResult.Cache;//当头部都无法解析时,直接缓存
  19. }
  20. int pos = byteBlock.Pos;//记录初始游标位置,防止本次无法解析时,回退游标。
  21. MyRequestInfo myRequestInfo = new MyRequestInfo();
  22. byteBlock.Read(out byte[] header, 3);//填充header
  23. //因为第一个字节表示所有长度,而DataType、OrderType已经包含在了header里面。
  24. //所有只需呀再读取header[0]-2个长度即可。
  25. byte bodyLength = (byte)(header[0] - 2);
  26. if (bodyLength > byteBlock.CanReadLen)
  27. {
  28. //body数据不足。
  29. byteBlock.Pos = pos;//回退游标
  30. return FilterResult.Cache;
  31. }
  32. else
  33. {
  34. byteBlock.Read(out byte[] body, bodyLength);//填充body
  35. myRequestInfo.Header = header;
  36. myRequestInfo.DataType = header[1];
  37. myRequestInfo.OrderType = header[2];
  38. myRequestInfo.Body = body;
  39. request = myRequestInfo;//赋值ref
  40. return FilterResult.Success;//返回成功
  41. }
  42. }
  43. }
  44. internal class MyRequestInfo : IRequestInfo
  45. {
  46. /// <summary>
  47. /// 自定义属性,Body
  48. /// </summary>
  49. public byte[] Body { get; internal set; }
  50. /// <summary>
  51. /// 自定义属性,Header
  52. /// </summary>
  53. public byte[] Header { get; internal set; }
  54. /// <summary>
  55. /// 自定义属性,DataType
  56. /// </summary>
  57. public byte DataType { get; internal set; }
  58. /// <summary>
  59. /// 自定义属性,OrderType
  60. /// </summary>
  61. public byte OrderType { get; internal set; }
  62. }