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.
 
 
 
 

55 lines
1.6 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 ClientWebSocket _webSocket;
  13. public Stream SendStream => RawReceiveStream;
  14. public Stream ReceiveStream => RawReceiveStream;
  15. public Stream RawReceiveStream { get; private set; }
  16. public async Task ConnectAsync(MqttClientOptions options)
  17. {
  18. var uri = options.Server;
  19. if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase))
  20. {
  21. uri = "ws://" + uri;
  22. }
  23. if (options.Port.HasValue)
  24. {
  25. uri += ":" + options.Port;
  26. }
  27. _webSocket = new ClientWebSocket();
  28. _webSocket.Options.KeepAliveInterval = options.KeepAlivePeriod;
  29. await _webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
  30. RawReceiveStream = new WebSocketStream(_webSocket);
  31. }
  32. public async Task DisconnectAsync()
  33. {
  34. RawReceiveStream = null;
  35. if (_webSocket == null)
  36. {
  37. return;
  38. }
  39. await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).ConfigureAwait(false);
  40. }
  41. public void Dispose()
  42. {
  43. _webSocket?.Dispose();
  44. }
  45. }
  46. }