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.

MqttWebSocketServerChannel.cs 1.4 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System;
  2. using System.IO;
  3. using System.Net.WebSockets;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MQTTnet.Core.Channel;
  7. using MQTTnet.Implementations;
  8. namespace MQTTnet.AspNetCore
  9. {
  10. public class MqttWebSocketServerChannel : IMqttCommunicationChannel, IDisposable
  11. {
  12. private WebSocket _webSocket;
  13. public MqttWebSocketServerChannel(WebSocket webSocket)
  14. {
  15. _webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
  16. SendStream = new WebSocketStream(_webSocket);
  17. ReceiveStream = SendStream;
  18. }
  19. public Stream SendStream { get; private set; }
  20. public Stream ReceiveStream { get; private set; }
  21. public Task ConnectAsync()
  22. {
  23. return Task.CompletedTask;
  24. }
  25. public async Task DisconnectAsync()
  26. {
  27. if (_webSocket == null)
  28. {
  29. return;
  30. }
  31. try
  32. {
  33. await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
  34. }
  35. finally
  36. {
  37. Dispose();
  38. }
  39. }
  40. public void Dispose()
  41. {
  42. SendStream?.Dispose();
  43. ReceiveStream?.Dispose();
  44. _webSocket?.Dispose();
  45. SendStream = null;
  46. ReceiveStream = null;
  47. _webSocket = null;
  48. }
  49. }
  50. }