Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 

54 righe
1.7 KiB

  1. using System;
  2. using System.Threading;
  3. using Windows.Networking.Sockets;
  4. using MQTTnet.Core.Adapter;
  5. using MQTTnet.Core.Serializer;
  6. using MQTTnet.Core.Server;
  7. namespace MQTTnet
  8. {
  9. public sealed class MqttServerAdapter : IMqttServerAdapter, IDisposable
  10. {
  11. private CancellationTokenSource _cancellationTokenSource;
  12. private StreamSocketListener _socket;
  13. public event EventHandler<MqttClientConnectedEventArgs> ClientConnected;
  14. public void Start(MqttServerOptions options)
  15. {
  16. if (_socket != null) throw new InvalidOperationException("Server is already started.");
  17. _cancellationTokenSource = new CancellationTokenSource();
  18. _socket = new StreamSocketListener();
  19. _socket.BindServiceNameAsync(options.Port.ToString()).AsTask().Wait();
  20. _socket.ConnectionReceived += ConnectionReceived;
  21. }
  22. private void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
  23. {
  24. var clientAdapter = new MqttChannelCommunicationAdapter(new MqttTcpChannel(args.Socket), new DefaultMqttV311PacketSerializer());
  25. var identifier = $"{args.Socket.Information.RemoteAddress}:{args.Socket.Information.RemotePort}";
  26. ClientConnected?.Invoke(this, new MqttClientConnectedEventArgs(identifier, clientAdapter));
  27. }
  28. public void Stop()
  29. {
  30. _cancellationTokenSource?.Dispose();
  31. if (_socket != null)
  32. {
  33. _socket.ConnectionReceived -= ConnectionReceived;
  34. }
  35. _socket?.Dispose();
  36. _socket = null;
  37. }
  38. public void Dispose()
  39. {
  40. Stop();
  41. }
  42. }
  43. }