Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

MqttWebSocketChannel.cs 1.6 KiB

pirms 7 gadiem
pirms 7 gadiem
pirms 7 gadiem
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 RawReceiveStream { get; private set; }
  14. public Stream SendStream => RawReceiveStream;
  15. public Stream ReceiveStream => RawReceiveStream;
  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).ConfigureAwait(false);
  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. }