Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

MqttPacketReader.cs 2.6 KiB

há 7 anos
há 7 anos
há 7 anos
há 7 anos
há 7 anos
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Threading.Tasks;
  5. using MQTTnet.Core.Exceptions;
  6. using MQTTnet.Core.Protocol;
  7. using MQTTnet.Core.Channel;
  8. using MQTTnet.Core.Packets;
  9. namespace MQTTnet.Core.Serializer
  10. {
  11. public sealed class MqttPacketReader : BinaryReader
  12. {
  13. private readonly MqttPacketHeader _header;
  14. public MqttPacketReader(Stream stream, MqttPacketHeader header)
  15. : base(stream)
  16. {
  17. _header = header;
  18. }
  19. public bool EndOfRemainingData => BaseStream.Position == _header.BodyLength;
  20. public override ushort ReadUInt16()
  21. {
  22. var buffer = ReadBytes(2);
  23. var temp = buffer[0];
  24. buffer[0] = buffer[1];
  25. buffer[1] = temp;
  26. return BitConverter.ToUInt16(buffer, 0);
  27. }
  28. public string ReadStringWithLengthPrefix()
  29. {
  30. var buffer = ReadWithLengthPrefix();
  31. return Encoding.UTF8.GetString(buffer, 0, buffer.Length);
  32. }
  33. public byte[] ReadWithLengthPrefix()
  34. {
  35. var length = ReadUInt16();
  36. return ReadBytes(length);
  37. }
  38. public byte[] ReadRemainingData()
  39. {
  40. return ReadBytes(_header.BodyLength - (int)BaseStream.Position);
  41. }
  42. public static MqttPacketHeader ReadHeaderFromSource(IMqttCommunicationChannel source)
  43. {
  44. var fixedHeader = (byte)source.Stream.ReadByte();
  45. var byteReader = new ByteReader(fixedHeader);
  46. byteReader.Read(4);
  47. var controlPacketType = (MqttControlPacketType)byteReader.Read(4);
  48. var bodyLength = ReadBodyLengthFromSource(source);
  49. return new MqttPacketHeader()
  50. {
  51. FixedHeader = fixedHeader,
  52. ControlPacketType = controlPacketType,
  53. BodyLength = bodyLength
  54. };
  55. }
  56. private static int ReadBodyLengthFromSource(IMqttCommunicationChannel source)
  57. {
  58. // Alorithm taken from http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html.
  59. var multiplier = 1;
  60. var value = 0;
  61. byte encodedByte;
  62. do
  63. {
  64. encodedByte = (byte)source.Stream.ReadByte();
  65. value += (encodedByte & 127) * multiplier;
  66. multiplier *= 128;
  67. if (multiplier > 128 * 128 * 128)
  68. {
  69. throw new MqttProtocolViolationException("Remaining length is ivalid.");
  70. }
  71. } while ((encodedByte & 128) != 0);
  72. return value;
  73. }
  74. }
  75. }