Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

MqttPacketWriter.cs 2.0 KiB

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