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.

MqttPacketWriter.cs 2.0 KiB

7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
7 jaren geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using MQTTnet.Core.Protocol;
  5. using System.Collections.Generic;
  6. namespace MQTTnet.Core.Serializer
  7. {
  8. public sealed class MqttPacketWriter : BinaryWriter
  9. {
  10. public MqttPacketWriter(Stream stream)
  11. : base(stream)
  12. {
  13. }
  14. public static byte BuildFixedHeader(MqttControlPacketType packetType, byte flags = 0)
  15. {
  16. var fixedHeader = (int)packetType << 4;
  17. fixedHeader |= flags;
  18. return (byte)fixedHeader;
  19. }
  20. public override void Write(ushort value)
  21. {
  22. var buffer = BitConverter.GetBytes(value);
  23. Write(buffer[1], buffer[0]);
  24. }
  25. public new void Write(params byte[] values)
  26. {
  27. base.Write(values);
  28. }
  29. public new void Write(byte value)
  30. {
  31. base.Write(value);
  32. }
  33. public void Write(ByteWriter value)
  34. {
  35. if (value == null) throw new ArgumentNullException(nameof(value));
  36. Write(value.Value);
  37. }
  38. public void WriteWithLengthPrefix(string value)
  39. {
  40. WriteWithLengthPrefix(Encoding.UTF8.GetBytes(value ?? string.Empty));
  41. }
  42. public void WriteWithLengthPrefix(byte[] value)
  43. {
  44. var length = (ushort)value.Length;
  45. Write(length);
  46. Write(value);
  47. }
  48. public static void BuildLengthHeader(int length, List<byte> header)
  49. {
  50. if (length == 0)
  51. {
  52. header.Add(0);
  53. return;
  54. }
  55. // Alorithm taken from http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html.
  56. var x = length;
  57. do
  58. {
  59. var encodedByte = x % 128;
  60. x = x / 128;
  61. if (x > 0)
  62. {
  63. encodedByte = encodedByte | 128;
  64. }
  65. header.Add((byte)encodedByte);
  66. } while (x > 0);
  67. }
  68. }
  69. }