Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

MqttServerAdapter.cs 2.3 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. }