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

69 lines
2.7 KiB

  1. using System;
  2. using System.Threading.Tasks;
  3. using MQTTnet.Core.Adapter;
  4. using MQTTnet.Core.Server;
  5. using Windows.Networking.Sockets;
  6. using Microsoft.Extensions.Logging;
  7. namespace MQTTnet.Implementations
  8. {
  9. public class MqttServerAdapter : IMqttServerAdapter, IDisposable
  10. {
  11. private readonly ILogger<MqttServerAdapter> _logger;
  12. private readonly IMqttCommunicationAdapterFactory _mqttCommunicationAdapterFactory;
  13. private StreamSocketListener _defaultEndpointSocket;
  14. public MqttServerAdapter(ILogger<MqttServerAdapter> logger, IMqttCommunicationAdapterFactory mqttCommunicationAdapterFactory)
  15. {
  16. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  17. _mqttCommunicationAdapterFactory = mqttCommunicationAdapterFactory ?? throw new ArgumentNullException(nameof(mqttCommunicationAdapterFactory));
  18. }
  19. public event EventHandler<MqttServerAdapterClientAcceptedEventArgs> ClientAccepted;
  20. public async Task StartAsync(MqttServerOptions 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. _defaultEndpointSocket?.Dispose();
  38. _defaultEndpointSocket = null;
  39. return Task.FromResult(0);
  40. }
  41. public void Dispose()
  42. {
  43. StopAsync();
  44. }
  45. private void AcceptDefaultEndpointConnectionsAsync(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
  46. {
  47. try
  48. {
  49. var clientAdapter = _mqttCommunicationAdapterFactory.CreateServerMqttCommunicationAdapter(new MqttTcpChannel(args.Socket));
  50. ClientAccepted?.Invoke(this, new MqttServerAdapterClientAcceptedEventArgs(clientAdapter));
  51. }
  52. catch (Exception exception)
  53. {
  54. _logger.LogError(new EventId(), exception, "Error while accepting connection at default endpoint.");
  55. }
  56. }
  57. }
  58. }