25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

83 lines
2.0 KiB

  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, Encoding.UTF8, true)
  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 WriteRemainingLength(int length, List<byte> target)
  49. {
  50. if (length == 0)
  51. {
  52. target.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. target.Add((byte)encodedByte);
  66. } while (x > 0);
  67. }
  68. }
  69. }