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.
 
 
 
 

64 rivejä
2.3 KiB

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