Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

75 строки
2.6 KiB

  1. #if WINDOWS_UWP
  2. using System;
  3. using System.Threading.Tasks;
  4. using Windows.Networking.Sockets;
  5. using MQTTnet.Adapter;
  6. using MQTTnet.Diagnostics;
  7. using MQTTnet.Serializer;
  8. using MQTTnet.Server;
  9. namespace MQTTnet.Implementations
  10. {
  11. public class MqttServerAdapter : IMqttServerAdapter, IDisposable
  12. {
  13. private readonly IMqttNetLogger _logger;
  14. private StreamSocketListener _defaultEndpointSocket;
  15. public MqttServerAdapter(IMqttNetLogger logger)
  16. {
  17. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  18. }
  19. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  20. public async Task StartAsync(IMqttServerOptions options)
  21. {
  22. if (options == null) throw new ArgumentNullException(nameof(options));
  23. if (_defaultEndpointSocket != null) throw new InvalidOperationException("Server is already started.");
  24. if (options.DefaultEndpointOptions.IsEnabled)
  25. {
  26. _defaultEndpointSocket = new StreamSocketListener();
  27. await _defaultEndpointSocket.BindServiceNameAsync(options.GetDefaultEndpointPort().ToString(), SocketProtectionLevel.PlainSocket);
  28. _defaultEndpointSocket.ConnectionReceived += AcceptDefaultEndpointConnectionsAsync;
  29. }
  30. if (options.TlsEndpointOptions.IsEnabled)
  31. {
  32. throw new NotSupportedException("TLS servers are not supported for UWP apps.");
  33. }
  34. }
  35. public Task StopAsync()
  36. {
  37. if (_defaultEndpointSocket != null)
  38. {
  39. _defaultEndpointSocket.ConnectionReceived -= AcceptDefaultEndpointConnectionsAsync;
  40. }
  41. _defaultEndpointSocket?.Dispose();
  42. _defaultEndpointSocket = null;
  43. return Task.FromResult(0);
  44. }
  45. public void Dispose()
  46. {
  47. StopAsync();
  48. }
  49. private void AcceptDefaultEndpointConnectionsAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
  50. {
  51. try
  52. {
  53. var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(args.Socket), new MqttPacketSerializer(), _logger);
  54. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  55. }
  56. catch (Exception exception)
  57. {
  58. _logger.Error<MqttServerAdapter>(exception, "Error while accepting connection at default endpoint.");
  59. }
  60. }
  61. }
  62. }
  63. #endif