Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

92 рядки
2.9 KiB

  1. using MQTTnet.Core.Channel;
  2. using MQTTnet.Core.Client;
  3. using System;
  4. using System.IO;
  5. using System.Net.WebSockets;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace MQTTnet.Implementations
  10. {
  11. public sealed class MqttWebSocketChannel : IMqttCommunicationChannel, IDisposable
  12. {
  13. private readonly MqttClientWebSocketOptions _options;
  14. private ClientWebSocket _webSocket = new ClientWebSocket();
  15. public MqttWebSocketChannel(MqttClientWebSocketOptions options)
  16. {
  17. _options = options ?? throw new ArgumentNullException(nameof(options));
  18. }
  19. public Stream RawReceiveStream { get; private set; }
  20. public Stream SendStream => RawReceiveStream;
  21. public Stream ReceiveStream => RawReceiveStream;
  22. public async Task ConnectAsync()
  23. {
  24. var uri = _options.Uri;
  25. if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase))
  26. {
  27. uri = "ws://" + uri;
  28. }
  29. _webSocket = new ClientWebSocket();
  30. if (_options.RequestHeaders != null)
  31. {
  32. foreach (var requestHeader in _options.RequestHeaders)
  33. {
  34. _webSocket.Options.SetRequestHeader(requestHeader.Key, requestHeader.Value);
  35. }
  36. }
  37. if (_options.SubProtocols != null)
  38. {
  39. foreach (var subProtocol in _options.SubProtocols)
  40. {
  41. _webSocket.Options.AddSubProtocol(subProtocol);
  42. }
  43. }
  44. if (_options.CookieContainer != null)
  45. {
  46. _webSocket.Options.Cookies = _options.CookieContainer;
  47. }
  48. if (_options.TlsOptions?.UseTls == true && _options.TlsOptions?.Certificates != null)
  49. {
  50. _webSocket.Options.ClientCertificates = new X509CertificateCollection();
  51. foreach (var certificate in _options.TlsOptions.Certificates)
  52. {
  53. _webSocket.Options.ClientCertificates.Add(new X509Certificate(certificate));
  54. }
  55. }
  56. await _webSocket.ConnectAsync(new Uri(uri), CancellationToken.None).ConfigureAwait(false);
  57. RawReceiveStream = new WebSocketStream(_webSocket);
  58. }
  59. public async Task DisconnectAsync()
  60. {
  61. RawReceiveStream = null;
  62. if (_webSocket == null)
  63. {
  64. return;
  65. }
  66. if (_webSocket.State == WebSocketState.Open || _webSocket.State == WebSocketState.Connecting)
  67. {
  68. await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).ConfigureAwait(false);
  69. }
  70. }
  71. public void Dispose()
  72. {
  73. _webSocket?.Dispose();
  74. _webSocket = null;
  75. }
  76. }
  77. }