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.
 
 
 
 

48 lines
1.3 KiB

  1. using MQTTnet.Core.Channel;
  2. using MQTTnet.Core.Client;
  3. using MQTTnet.Core.Exceptions;
  4. using System;
  5. using System.IO;
  6. using System.Net.WebSockets;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace MQTTnet.Implementations
  10. {
  11. public sealed class MqttWebSocketChannel : IMqttCommunicationChannel, IDisposable
  12. {
  13. private ClientWebSocket _webSocket = new ClientWebSocket();
  14. public Stream ReceiveStream { get; private set; }
  15. public Stream SendStream { get; private set; }
  16. public async Task ConnectAsync(MqttClientOptions options)
  17. {
  18. _webSocket = null;
  19. try
  20. {
  21. _webSocket = new ClientWebSocket();
  22. await _webSocket.ConnectAsync(new Uri(options.Server), CancellationToken.None);
  23. ReceiveStream = SendStream = new WebSocketStream(_webSocket);
  24. }
  25. catch (WebSocketException exception)
  26. {
  27. throw new MqttCommunicationException(exception);
  28. }
  29. }
  30. public Task DisconnectAsync()
  31. {
  32. ReceiveStream = null;
  33. return _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
  34. }
  35. public void Dispose()
  36. {
  37. _webSocket?.Dispose();
  38. }
  39. }
  40. }