Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 

84 lignes
2.9 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 MqttTcpServerAdapter : IMqttServerAdapter
  12. {
  13. private readonly IMqttNetChildLogger _logger;
  14. private StreamSocketListener _defaultEndpointSocket;
  15. public MqttTcpServerAdapter(IMqttNetChildLogger logger)
  16. {
  17. if (logger == null) throw new ArgumentNullException(nameof(logger));
  18. _logger = logger.CreateChildLogger(nameof(MqttTcpServerAdapter));
  19. }
  20. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  21. public async Task StartAsync(IMqttServerOptions options)
  22. {
  23. if (options == null) throw new ArgumentNullException(nameof(options));
  24. if (_defaultEndpointSocket != null) throw new InvalidOperationException("Server is already started.");
  25. if (options.DefaultEndpointOptions.IsEnabled)
  26. {
  27. _defaultEndpointSocket = new StreamSocketListener();
  28. // This also affects the client sockets.
  29. _defaultEndpointSocket.Control.NoDelay = true;
  30. _defaultEndpointSocket.Control.KeepAlive = true;
  31. _defaultEndpointSocket.Control.QualityOfService = SocketQualityOfService.LowLatency;
  32. _defaultEndpointSocket.ConnectionReceived += AcceptDefaultEndpointConnectionsAsync;
  33. await _defaultEndpointSocket.BindServiceNameAsync(options.GetDefaultEndpointPort().ToString(), SocketProtectionLevel.PlainSocket);
  34. }
  35. if (options.TlsEndpointOptions.IsEnabled)
  36. {
  37. throw new NotSupportedException("TLS servers are not supported for UWP apps.");
  38. }
  39. }
  40. public Task StopAsync()
  41. {
  42. if (_defaultEndpointSocket != null)
  43. {
  44. _defaultEndpointSocket.ConnectionReceived -= AcceptDefaultEndpointConnectionsAsync;
  45. }
  46. _defaultEndpointSocket?.Dispose();
  47. _defaultEndpointSocket = null;
  48. return Task.FromResult(0);
  49. }
  50. public void Dispose()
  51. {
  52. StopAsync().GetAwaiter().GetResult();
  53. }
  54. private void AcceptDefaultEndpointConnectionsAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
  55. {
  56. try
  57. {
  58. var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(args.Socket), new MqttPacketSerializer(), _logger);
  59. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  60. }
  61. catch (Exception exception)
  62. {
  63. _logger.Error(exception, "Error while accepting connection at default endpoint.");
  64. }
  65. }
  66. }
  67. }
  68. #endif