25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TestMqttServerAdapter.cs 2.2 KiB

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