Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

MqttPacketReader.cs 3.9 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MQTTnet.Exceptions;
  8. using MQTTnet.Packets;
  9. using MQTTnet.Protocol;
  10. namespace MQTTnet.Serializer
  11. {
  12. public sealed class MqttPacketReader : BinaryReader
  13. {
  14. private readonly MqttPacketHeader _header;
  15. public MqttPacketReader(MqttPacketHeader header, Stream bodyStream)
  16. : base(bodyStream, Encoding.UTF8, true)
  17. {
  18. _header = header;
  19. }
  20. public bool EndOfRemainingData => BaseStream.Position == _header.BodyLength;
  21. public static async Task<MqttPacketHeader> ReadHeaderFromSourceAsync(Stream stream, CancellationToken cancellationToken)
  22. {
  23. // Wait for the next package which starts with the header. At this point there will probably
  24. // some large delay and thus the thread should be put back to the pool (await). So ReadByte()
  25. // is not an option here.
  26. var buffer = new byte[1];
  27. var readCount = await stream.ReadAsync(buffer, 0, 1, cancellationToken).ConfigureAwait(false);
  28. if (readCount <= 0)
  29. {
  30. return null;
  31. }
  32. var fixedHeader = buffer[0];
  33. var controlPacketType = (MqttControlPacketType)(fixedHeader >> 4);
  34. var bodyLength = await ReadBodyLengthFromSourceAsync(stream, cancellationToken).ConfigureAwait(false);
  35. return new MqttPacketHeader
  36. {
  37. FixedHeader = fixedHeader,
  38. ControlPacketType = controlPacketType,
  39. BodyLength = bodyLength
  40. };
  41. }
  42. public override ushort ReadUInt16()
  43. {
  44. var buffer = ReadBytes(2);
  45. var temp = buffer[0];
  46. buffer[0] = buffer[1];
  47. buffer[1] = temp;
  48. return BitConverter.ToUInt16(buffer, 0);
  49. }
  50. public string ReadStringWithLengthPrefix()
  51. {
  52. var buffer = ReadWithLengthPrefix();
  53. if (buffer.Length == 0)
  54. {
  55. return string.Empty;
  56. }
  57. return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
  58. }
  59. public byte[] ReadWithLengthPrefix()
  60. {
  61. var length = ReadUInt16();
  62. if (length == 0)
  63. {
  64. return new byte[0];
  65. }
  66. return ReadBytes(length);
  67. }
  68. public byte[] ReadRemainingData()
  69. {
  70. return ReadBytes(_header.BodyLength - (int)BaseStream.Position);
  71. }
  72. private static async Task<int> ReadBodyLengthFromSourceAsync(Stream stream, CancellationToken cancellationToken)
  73. {
  74. // Alorithm taken from http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html.
  75. var multiplier = 1;
  76. var value = 0;
  77. byte encodedByte;
  78. var buffer = new byte[1];
  79. var readBytes = new List<byte>();
  80. do
  81. {
  82. if (cancellationToken.IsCancellationRequested)
  83. {
  84. throw new TaskCanceledException();
  85. }
  86. var readCount = await stream.ReadAsync(buffer, 0, 1, cancellationToken).ConfigureAwait(false);
  87. if (readCount <= 0)
  88. {
  89. throw new MqttCommunicationException("Connection closed while reading remaining length data.");
  90. }
  91. encodedByte = buffer[0];
  92. readBytes.Add(encodedByte);
  93. value += (byte)(encodedByte & 127) * multiplier;
  94. multiplier *= 128;
  95. if (multiplier > 128 * 128 * 128)
  96. {
  97. throw new MqttProtocolViolationException($"Remaining length is invalid (Data={string.Join(",", readBytes)}).");
  98. }
  99. } while ((encodedByte & 128) != 0);
  100. return value;
  101. }
  102. }
  103. }