25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MqttWebSocketChannel.cs 1.3 KiB

7 년 전
7 년 전
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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 SendStream => RawStream;
  15. public Stream ReceiveStream => RawStream;
  16. public Stream RawStream { get; private set; }
  17. public async Task ConnectAsync(MqttClientOptions options)
  18. {
  19. _webSocket = null;
  20. try
  21. {
  22. _webSocket = new ClientWebSocket();
  23. await _webSocket.ConnectAsync(new Uri(options.Server), CancellationToken.None);
  24. RawStream = new WebSocketStream(_webSocket);
  25. }
  26. catch (WebSocketException exception)
  27. {
  28. throw new MqttCommunicationException(exception);
  29. }
  30. }
  31. public Task DisconnectAsync()
  32. {
  33. RawStream = null;
  34. return _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
  35. }
  36. public void Dispose()
  37. {
  38. _webSocket?.Dispose();
  39. }
  40. }
  41. }