You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
3.1 KiB

8 months ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Mirle.Component.SocketDirver.FrameBuilder
  5. {
  6. /// <summary>
  7. /// Google Protobuffer 訊息加解密類別
  8. /// </summary>
  9. public class ProtobufferFrameBulder : IFrameBuilder
  10. {
  11. /// <inheritdoc/>
  12. public byte[] EncodeFrame(byte[] payload)
  13. {
  14. List<byte> list = new List<byte>();
  15. long num = payload.LongLength;
  16. if (num <= 125)
  17. {
  18. byte item = (byte)num;
  19. list.Add(item);
  20. }
  21. else if (num <= 65535)
  22. {
  23. byte item2 = 126;
  24. list.Add(item2);
  25. byte[] bytes = BitConverter.GetBytes(num);
  26. list.Add(bytes[1]);
  27. list.Add(bytes[0]);
  28. }
  29. else
  30. {
  31. byte item3 = 127;
  32. list.Add(item3);
  33. byte[] bytes2 = BitConverter.GetBytes(num);
  34. list.Add(bytes2[7]);
  35. list.Add(bytes2[6]);
  36. list.Add(bytes2[5]);
  37. list.Add(bytes2[4]);
  38. list.Add(bytes2[3]);
  39. list.Add(bytes2[2]);
  40. list.Add(bytes2[1]);
  41. list.Add(bytes2[0]);
  42. }
  43. list.AddRange(payload);
  44. return list.ToArray();
  45. }
  46. /// <inheritdoc/>
  47. public bool TryDecodeFrame(byte[] buffer, out int receiveCount, out byte[] payload)
  48. {
  49. try
  50. {
  51. int num = buffer.AsEnumerable().First() & 0x7F;
  52. int num2 = 1;
  53. int num3 = 0;
  54. if (num <= 125)
  55. {
  56. num2 = 1;
  57. num3 = num;
  58. }
  59. else
  60. {
  61. switch (num)
  62. {
  63. case 126:
  64. {
  65. num2 = 3;
  66. byte[] array2 = buffer.Skip(1).Take(2).ToArray();
  67. num3 = array2[0] * 256 + array2[1];
  68. break;
  69. }
  70. case 127:
  71. {
  72. num2 = 9;
  73. byte[] array = buffer.Skip(1).Take(8).ToArray();
  74. int num4 = 1;
  75. for (int i = 0; i < 8; i++)
  76. {
  77. num3 += array[8 - i - 1] * num4;
  78. num4 *= 256;
  79. }
  80. break;
  81. }
  82. }
  83. }
  84. receiveCount = num2 + num3;
  85. payload = buffer.Skip(num2).Take(num3).ToArray();
  86. return true;
  87. }
  88. catch (Exception ex)
  89. {
  90. Console.WriteLine(ex.ToString());
  91. receiveCount = 0;
  92. payload = null;
  93. return false;
  94. }
  95. }
  96. }
  97. }