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.

TestMqttServerAdapter.cs 1.9 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Threading.Tasks;
  3. using MQTTnet.Core.Adapter;
  4. using MQTTnet.Core.Server;
  5. using MQTTnet.Core.Client;
  6. namespace MQTTnet.Core.Tests
  7. {
  8. public class TestMqttServerAdapter : IMqttServerAdapter
  9. {
  10. public event Action<IMqttCommunicationAdapter> ClientAccepted;
  11. public async Task<MqttClient> ConnectTestClient(IMqttServer server, string clientId, MqttApplicationMessage willMessage = null)
  12. {
  13. var adapterA = new TestMqttCommunicationAdapter();
  14. var adapterB = new TestMqttCommunicationAdapter();
  15. adapterA.Partner = adapterB;
  16. adapterB.Partner = adapterA;
  17. var client = new MqttClient(new MqttCommunicationAdapterFactory(adapterA));
  18. var connected = WaitForClientToConnect(server, clientId);
  19. FireClientAcceptedEvent(adapterB);
  20. await client.ConnectAsync(new MqttClientTcpOptions { ClientId = clientId, WillMessage = willMessage });
  21. await connected;
  22. return client;
  23. }
  24. private static Task WaitForClientToConnect(IMqttServer s, string clientId)
  25. {
  26. var tcs = new TaskCompletionSource<object>();
  27. void Handler(object sender, MqttClientConnectedEventArgs args)
  28. {
  29. if (args.Client.ClientId == clientId)
  30. {
  31. s.ClientConnected -= Handler;
  32. tcs.SetResult(null);
  33. }
  34. }
  35. s.ClientConnected += Handler;
  36. return tcs.Task;
  37. }
  38. private void FireClientAcceptedEvent(IMqttCommunicationAdapter adapter)
  39. {
  40. ClientAccepted?.Invoke(adapter);
  41. }
  42. public Task StartAsync(MqttServerOptions options)
  43. {
  44. return Task.FromResult(0);
  45. }
  46. public Task StopAsync()
  47. {
  48. return Task.FromResult(0);
  49. }
  50. }
  51. }