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.

MqttTcpServerAdapter.Uwp.cs 2.6 KiB

il y a 7 ans
il y a 7 ans
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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, IDisposable
  12. {
  13. private readonly IMqttNetLogger _logger;
  14. private StreamSocketListener _defaultEndpointSocket;
  15. public MqttTcpServerAdapter(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<MqttTcpServerAdapter>(exception, "Error while accepting connection at default endpoint.");
  59. }
  60. }
  61. }
  62. }
  63. #endif