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.
 
 
 
 

56 rindas
1.7 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.Threading;
  7. using System.Threading.Tasks;
  8. namespace MQTTnet.Implementations
  9. {
  10. public sealed class MqttWebSocketChannel : IMqttCommunicationChannel, IDisposable
  11. {
  12. private readonly MqttClientWebSocketOptions _options;
  13. private ClientWebSocket _webSocket;
  14. public MqttWebSocketChannel(MqttClientWebSocketOptions options)
  15. {
  16. _options = options ?? throw new ArgumentNullException(nameof(options));
  17. }
  18. public Stream SendStream => RawReceiveStream;
  19. public Stream ReceiveStream => RawReceiveStream;
  20. public Stream RawReceiveStream { get; private set; }
  21. public async Task ConnectAsync()
  22. {
  23. var uri = _options.Uri;
  24. if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase))
  25. {
  26. uri = "ws://" + uri;
  27. }
  28. _webSocket = new ClientWebSocket();
  29. _webSocket.Options.KeepAliveInterval = _options.KeepAlivePeriod;
  30. await _webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
  31. RawReceiveStream = new WebSocketStream(_webSocket);
  32. }
  33. public async Task DisconnectAsync()
  34. {
  35. RawReceiveStream = null;
  36. if (_webSocket == null)
  37. {
  38. return;
  39. }
  40. await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).ConfigureAwait(false);
  41. }
  42. public void Dispose()
  43. {
  44. _webSocket?.Dispose();
  45. }
  46. }
  47. }