您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

MqttChannelAdapter.cs 8.0 KiB

6 年前
6 年前
6 年前
6 年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net.Sockets;
  5. using System.Runtime.InteropServices;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using MQTTnet.Channel;
  9. using MQTTnet.Diagnostics;
  10. using MQTTnet.Exceptions;
  11. using MQTTnet.Packets;
  12. using MQTTnet.Serializer;
  13. namespace MQTTnet.Adapter
  14. {
  15. public sealed class MqttChannelAdapter : IMqttChannelAdapter
  16. {
  17. private const uint ErrorOperationAborted = 0x800703E3;
  18. private const int ReadBufferSize = 4096; // TODO: Move buffer size to config
  19. private readonly IMqttNetLogger _logger;
  20. private readonly IMqttChannel _channel;
  21. private bool _isDisposed;
  22. public MqttChannelAdapter(IMqttChannel channel, IMqttPacketSerializer serializer, IMqttNetLogger logger)
  23. {
  24. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  25. _channel = channel ?? throw new ArgumentNullException(nameof(channel));
  26. PacketSerializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
  27. }
  28. public IMqttPacketSerializer PacketSerializer { get; }
  29. public Task ConnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
  30. {
  31. ThrowIfDisposed();
  32. _logger.Verbose<MqttChannelAdapter>("Connecting [Timeout={0}]", timeout);
  33. return ExecuteAndWrapExceptionAsync(() =>
  34. Internal.TaskExtensions.TimeoutAfter(ct => _channel.ConnectAsync(ct), timeout, cancellationToken));
  35. }
  36. public Task DisconnectAsync(TimeSpan timeout, CancellationToken cancellationToken)
  37. {
  38. ThrowIfDisposed();
  39. _logger.Verbose<MqttChannelAdapter>("Disconnecting [Timeout={0}]", timeout);
  40. return ExecuteAndWrapExceptionAsync(() =>
  41. Internal.TaskExtensions.TimeoutAfter(ct => _channel.DisconnectAsync(), timeout, cancellationToken));
  42. }
  43. public async Task SendPacketsAsync(TimeSpan timeout, IEnumerable<MqttBasePacket> packets, CancellationToken cancellationToken)
  44. {
  45. ThrowIfDisposed();
  46. foreach (var packet in packets)
  47. {
  48. if (packet == null)
  49. {
  50. continue;
  51. }
  52. await SendPacketAsync(timeout, cancellationToken, packet).ConfigureAwait(false);
  53. }
  54. }
  55. private Task SendPacketAsync(TimeSpan timeout, CancellationToken cancellationToken, MqttBasePacket packet)
  56. {
  57. return ExecuteAndWrapExceptionAsync(() =>
  58. {
  59. _logger.Verbose<MqttChannelAdapter>("TX >>> {0} [Timeout={1}]", packet, timeout);
  60. var packetData = PacketSerializer.Serialize(packet);
  61. return Internal.TaskExtensions.TimeoutAfter(ct => _channel.WriteAsync(
  62. packetData.Array,
  63. packetData.Offset,
  64. packetData.Count,
  65. ct), timeout, cancellationToken);
  66. });
  67. }
  68. public async Task<MqttBasePacket> ReceivePacketAsync(TimeSpan timeout, CancellationToken cancellationToken)
  69. {
  70. ThrowIfDisposed();
  71. MqttBasePacket packet = null;
  72. await ExecuteAndWrapExceptionAsync(async () =>
  73. {
  74. ReceivedMqttPacket receivedMqttPacket = null;
  75. try
  76. {
  77. if (timeout > TimeSpan.Zero)
  78. {
  79. receivedMqttPacket = await Internal.TaskExtensions.TimeoutAfter(ct => ReceiveAsync(_channel, ct), timeout, cancellationToken).ConfigureAwait(false);
  80. }
  81. else
  82. {
  83. receivedMqttPacket = await ReceiveAsync(_channel, cancellationToken).ConfigureAwait(false);
  84. }
  85. if (receivedMqttPacket == null || cancellationToken.IsCancellationRequested)
  86. {
  87. throw new TaskCanceledException();
  88. }
  89. packet = PacketSerializer.Deserialize(receivedMqttPacket.Header, receivedMqttPacket.Body);
  90. if (packet == null)
  91. {
  92. throw new MqttProtocolViolationException("Received malformed packet.");
  93. }
  94. _logger.Verbose<MqttChannelAdapter>("RX <<< {0}", packet);
  95. }
  96. finally
  97. {
  98. receivedMqttPacket?.Dispose();
  99. }
  100. }).ConfigureAwait(false);
  101. return packet;
  102. }
  103. private static async Task<ReceivedMqttPacket> ReceiveAsync(IMqttChannel channel, CancellationToken cancellationToken)
  104. {
  105. var header = await MqttPacketReader.ReadHeaderAsync(channel, cancellationToken).ConfigureAwait(false);
  106. if (header == null)
  107. {
  108. return null;
  109. }
  110. if (header.BodyLength == 0)
  111. {
  112. return new ReceivedMqttPacket(header, new MemoryStream(new byte[0], false));
  113. }
  114. var body = new MemoryStream(header.BodyLength);
  115. var buffer = new byte[Math.Min(ReadBufferSize, header.BodyLength)];
  116. while (body.Length < header.BodyLength)
  117. {
  118. var bytesLeft = header.BodyLength - (int)body.Length;
  119. if (bytesLeft > buffer.Length)
  120. {
  121. bytesLeft = buffer.Length;
  122. }
  123. var readBytesCount = await channel.ReadAsync(buffer, 0, bytesLeft, cancellationToken).ConfigureAwait(false);
  124. // Check if the client closed the connection before sending the full body.
  125. if (readBytesCount == 0)
  126. {
  127. throw new MqttCommunicationException("Connection closed while reading remaining packet body.");
  128. }
  129. // Here is no need to await because internally only an array is used and no real I/O operation is made.
  130. // Using async here will only generate overhead.
  131. body.Write(buffer, 0, readBytesCount);
  132. }
  133. body.Seek(0L, SeekOrigin.Begin);
  134. return new ReceivedMqttPacket(header, body);
  135. }
  136. private static async Task ExecuteAndWrapExceptionAsync(Func<Task> action)
  137. {
  138. try
  139. {
  140. await action().ConfigureAwait(false);
  141. }
  142. catch (TaskCanceledException)
  143. {
  144. throw;
  145. }
  146. catch (OperationCanceledException)
  147. {
  148. throw;
  149. }
  150. catch (MqttCommunicationTimedOutException)
  151. {
  152. throw;
  153. }
  154. catch (MqttCommunicationException)
  155. {
  156. throw;
  157. }
  158. catch (COMException comException)
  159. {
  160. if ((uint)comException.HResult == ErrorOperationAborted)
  161. {
  162. throw new OperationCanceledException();
  163. }
  164. throw new MqttCommunicationException(comException);
  165. }
  166. catch (IOException exception)
  167. {
  168. if (exception.InnerException is SocketException socketException)
  169. {
  170. if (socketException.SocketErrorCode == SocketError.ConnectionAborted)
  171. {
  172. throw new OperationCanceledException();
  173. }
  174. }
  175. throw new MqttCommunicationException(exception);
  176. }
  177. catch (Exception exception)
  178. {
  179. throw new MqttCommunicationException(exception);
  180. }
  181. }
  182. public void Dispose()
  183. {
  184. _isDisposed = true;
  185. _channel?.Dispose();
  186. }
  187. private void ThrowIfDisposed()
  188. {
  189. if (_isDisposed)
  190. {
  191. throw new ObjectDisposedException(nameof(MqttChannelAdapter));
  192. }
  193. }
  194. }
  195. }