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.
 
 
 
 

76 rivejä
2.9 KiB

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