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.
 
 
 
 

68 lines
2.2 KiB

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