You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

57 lines
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 = new ClientWebSocket();
  14. public MqttWebSocketChannel(MqttClientWebSocketOptions options)
  15. {
  16. _options = options ?? throw new ArgumentNullException(nameof(options));
  17. }
  18. public Stream RawReceiveStream { get; private set; }
  19. public Stream SendStream => RawReceiveStream;
  20. public Stream ReceiveStream => RawReceiveStream;
  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).ConfigureAwait(false);
  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. }