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.

MqttServerTests.cs 27 KiB

7 anni fa
7 anni fa
6 anni fa
7 anni fa
6 anni fa
6 anni fa
6 anni fa
6 anni fa
6 anni fa
6 anni fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using MQTTnet.Client;
  3. using MQTTnet.Diagnostics;
  4. using MQTTnet.Protocol;
  5. using MQTTnet.Server;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MQTTnet.Adapter;
  13. using MQTTnet.Implementations;
  14. namespace MQTTnet.Core.Tests
  15. {
  16. [TestClass]
  17. public class MqttServerTests
  18. {
  19. [TestMethod]
  20. public void MqttServer_PublishSimple_AtMostOnce()
  21. {
  22. TestPublishAsync(
  23. "A/B/C",
  24. MqttQualityOfServiceLevel.AtMostOnce,
  25. "A/B/C",
  26. MqttQualityOfServiceLevel.AtMostOnce,
  27. 1).Wait();
  28. }
  29. [TestMethod]
  30. public void MqttServer_PublishSimple_AtLeastOnce()
  31. {
  32. TestPublishAsync(
  33. "A/B/C",
  34. MqttQualityOfServiceLevel.AtLeastOnce,
  35. "A/B/C",
  36. MqttQualityOfServiceLevel.AtLeastOnce,
  37. 1).Wait();
  38. }
  39. [TestMethod]
  40. public void MqttServer_PublishSimple_ExactlyOnce()
  41. {
  42. TestPublishAsync(
  43. "A/B/C",
  44. MqttQualityOfServiceLevel.ExactlyOnce,
  45. "A/B/C",
  46. MqttQualityOfServiceLevel.ExactlyOnce,
  47. 1).Wait();
  48. }
  49. [TestMethod]
  50. public async Task MqttServer_WillMessage()
  51. {
  52. var serverAdapter = new TestMqttServerAdapter();
  53. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  54. var receivedMessagesCount = 0;
  55. try
  56. {
  57. await s.StartAsync(new MqttServerOptions());
  58. var willMessage = new MqttApplicationMessageBuilder().WithTopic("My/last/will").WithAtMostOnceQoS().Build();
  59. var c1 = await serverAdapter.ConnectTestClient("c1");
  60. var c2 = await serverAdapter.ConnectTestClient("c2", willMessage);
  61. c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  62. await c1.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
  63. await c2.DisconnectAsync();
  64. await Task.Delay(1000);
  65. await c1.DisconnectAsync();
  66. }
  67. finally
  68. {
  69. await s.StopAsync();
  70. }
  71. Assert.AreEqual(0, receivedMessagesCount);
  72. }
  73. [TestMethod]
  74. public async Task MqttServer_SubscribeUnsubscribe()
  75. {
  76. var serverAdapter = new TestMqttServerAdapter();
  77. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  78. var receivedMessagesCount = 0;
  79. try
  80. {
  81. await s.StartAsync(new MqttServerOptions());
  82. var c1 = await serverAdapter.ConnectTestClient("c1");
  83. var c2 = await serverAdapter.ConnectTestClient("c2");
  84. c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  85. var message = new MqttApplicationMessageBuilder().WithTopic("a").WithAtLeastOnceQoS().Build();
  86. await c2.PublishAsync(message);
  87. await Task.Delay(1000);
  88. Assert.AreEqual(0, receivedMessagesCount);
  89. var subscribeEventCalled = false;
  90. s.ClientSubscribedTopic += (_, e) =>
  91. {
  92. subscribeEventCalled = e.TopicFilter.Topic == "a" && e.ClientId == "c1";
  93. };
  94. await c1.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce));
  95. await Task.Delay(500);
  96. Assert.IsTrue(subscribeEventCalled, "Subscribe event not called.");
  97. await c2.PublishAsync(message);
  98. await Task.Delay(500);
  99. Assert.AreEqual(1, receivedMessagesCount);
  100. var unsubscribeEventCalled = false;
  101. s.ClientUnsubscribedTopic += (_, e) =>
  102. {
  103. unsubscribeEventCalled = e.TopicFilter == "a" && e.ClientId == "c1";
  104. };
  105. await c1.UnsubscribeAsync("a");
  106. await Task.Delay(500);
  107. Assert.IsTrue(unsubscribeEventCalled, "Unsubscribe event not called.");
  108. await c2.PublishAsync(message);
  109. await Task.Delay(1000);
  110. Assert.AreEqual(1, receivedMessagesCount);
  111. }
  112. finally
  113. {
  114. await s.StopAsync();
  115. }
  116. await Task.Delay(500);
  117. Assert.AreEqual(1, receivedMessagesCount);
  118. }
  119. [TestMethod]
  120. public async Task MqttServer_Publish()
  121. {
  122. var serverAdapter = new TestMqttServerAdapter();
  123. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  124. var receivedMessagesCount = 0;
  125. try
  126. {
  127. await s.StartAsync(new MqttServerOptions());
  128. var c1 = await serverAdapter.ConnectTestClient("c1");
  129. c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  130. var message = new MqttApplicationMessageBuilder().WithTopic("a").WithAtLeastOnceQoS().Build();
  131. await c1.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce));
  132. await s.PublishAsync(message);
  133. await Task.Delay(500);
  134. }
  135. finally
  136. {
  137. await s.StopAsync();
  138. }
  139. Assert.AreEqual(1, receivedMessagesCount);
  140. }
  141. [TestMethod]
  142. public async Task MqttServer_Publish_MultipleClients()
  143. {
  144. var serverAdapter = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger());
  145. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  146. var receivedMessagesCount = 0;
  147. var locked = new object();
  148. var clientOptions = new MqttClientOptionsBuilder()
  149. .WithTcpServer("localhost")
  150. .Build();
  151. var clientOptions2 = new MqttClientOptionsBuilder()
  152. .WithTcpServer("localhost")
  153. .Build();
  154. try
  155. {
  156. await s.StartAsync(new MqttServerOptions());
  157. var c1 = new MqttFactory().CreateMqttClient();
  158. var c2 = new MqttFactory().CreateMqttClient();
  159. await c1.ConnectAsync(clientOptions);
  160. await c2.ConnectAsync(clientOptions2);
  161. c1.ApplicationMessageReceived += (_, __) =>
  162. {
  163. lock (locked)
  164. {
  165. receivedMessagesCount++;
  166. }
  167. };
  168. c2.ApplicationMessageReceived += (_, __) =>
  169. {
  170. lock (locked)
  171. {
  172. receivedMessagesCount++;
  173. }
  174. };
  175. var message = new MqttApplicationMessageBuilder().WithTopic("a").WithAtLeastOnceQoS().Build();
  176. await c1.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce));
  177. await c2.SubscribeAsync(new TopicFilter("a", MqttQualityOfServiceLevel.AtLeastOnce));
  178. //await Task.WhenAll(Publish(c1, message), Publish(c2, message));
  179. await Publish(c1, message);
  180. await Task.Delay(500);
  181. }
  182. finally
  183. {
  184. await s.StopAsync();
  185. }
  186. Assert.AreEqual(2000, receivedMessagesCount);
  187. }
  188. private static async Task Publish(IMqttClient c1, MqttApplicationMessage message)
  189. {
  190. for (int i = 0; i < 1000; i++)
  191. {
  192. await c1.PublishAsync(message);
  193. }
  194. }
  195. [TestMethod]
  196. public async Task MqttServer_ShutdownDisconnectsClientsGracefully()
  197. {
  198. var serverAdapter = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger());
  199. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  200. var clientOptions = new MqttClientOptionsBuilder()
  201. .WithTcpServer("localhost")
  202. .Build();
  203. var disconnectCalled = 0;
  204. await s.StartAsync(new MqttServerOptions());
  205. var c1 = new MqttFactory().CreateMqttClient();
  206. c1.Disconnected += (sender, args) => disconnectCalled++;
  207. await c1.ConnectAsync(clientOptions);
  208. await Task.Delay(100);
  209. await s.StopAsync();
  210. await Task.Delay(100);
  211. Assert.AreEqual(1, disconnectCalled);
  212. }
  213. [TestMethod]
  214. public async Task MqttServer_HandleCleanDisconnect()
  215. {
  216. MqttNetGlobalLogger.LogMessagePublished += (_, e) =>
  217. {
  218. System.Diagnostics.Debug.WriteLine($"[{e.TraceMessage.Timestamp:s}] {e.TraceMessage.Source} {e.TraceMessage.Message}");
  219. };
  220. var serverAdapter = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger());
  221. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  222. var clientConnectedCalled = 0;
  223. var clientDisconnectedCalled = 0;
  224. s.ClientConnected += (_, __) => clientConnectedCalled++;
  225. s.ClientDisconnected += (_, __) => clientDisconnectedCalled++;
  226. var clientOptions = new MqttClientOptionsBuilder()
  227. .WithTcpServer("localhost")
  228. .Build();
  229. await s.StartAsync(new MqttServerOptions());
  230. var c1 = new MqttFactory().CreateMqttClient();
  231. await c1.ConnectAsync(clientOptions);
  232. await Task.Delay(100);
  233. await c1.DisconnectAsync();
  234. await Task.Delay(100);
  235. await s.StopAsync();
  236. await Task.Delay(100);
  237. Assert.AreEqual(clientConnectedCalled, clientDisconnectedCalled);
  238. }
  239. [TestMethod]
  240. public async Task MqttServer_LotsOfRetainedMessages()
  241. {
  242. const int ClientCount = 100;
  243. var server = new MqttFactory().CreateMqttServer();
  244. try
  245. {
  246. await server.StartAsync(new MqttServerOptionsBuilder().Build());
  247. Parallel.For(
  248. 0,
  249. ClientCount,
  250. new ParallelOptions { MaxDegreeOfParallelism = 10 },
  251. i =>
  252. {
  253. using (var client = new MqttFactory().CreateMqttClient())
  254. {
  255. client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build())
  256. .GetAwaiter().GetResult();
  257. for (var j = 0; j < 10; j++)
  258. {
  259. // Clear retained message.
  260. client.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("r" + i)
  261. .WithPayload(new byte[0]).WithRetainFlag().Build()).GetAwaiter().GetResult();
  262. // Set retained message.
  263. client.PublishAsync(new MqttApplicationMessageBuilder().WithTopic("r" + i)
  264. .WithPayload("value" + j).WithRetainFlag().Build()).GetAwaiter().GetResult();
  265. }
  266. client.DisconnectAsync().GetAwaiter().GetResult();
  267. }
  268. });
  269. await Task.Delay(100);
  270. var retainedMessages = server.GetRetainedMessages();
  271. Assert.AreEqual(ClientCount, retainedMessages.Count);
  272. for (var i = 0; i < ClientCount; i++)
  273. {
  274. Assert.IsTrue(retainedMessages.Any(m => m.Topic == "r" + i));
  275. }
  276. }
  277. finally
  278. {
  279. await server.StopAsync();
  280. }
  281. }
  282. [TestMethod]
  283. public async Task MqttServer_RetainedMessagesFlow()
  284. {
  285. var retainedMessage = new MqttApplicationMessageBuilder().WithTopic("r").WithPayload("r").WithRetainFlag().Build();
  286. var serverAdapter = new TestMqttServerAdapter();
  287. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  288. await s.StartAsync(new MqttServerOptions());
  289. var c1 = await serverAdapter.ConnectTestClient("c1");
  290. await c1.PublishAsync(retainedMessage);
  291. Thread.Sleep(500);
  292. await c1.DisconnectAsync();
  293. Thread.Sleep(500);
  294. var receivedMessages = 0;
  295. var c2 = await serverAdapter.ConnectTestClient("c2");
  296. c2.ApplicationMessageReceived += (_, e) =>
  297. {
  298. receivedMessages++;
  299. };
  300. for (var i = 0; i < 5; i++)
  301. {
  302. await c2.UnsubscribeAsync("r");
  303. await Task.Delay(500);
  304. Assert.AreEqual(i, receivedMessages);
  305. await c2.SubscribeAsync("r");
  306. await Task.Delay(500);
  307. Assert.AreEqual(i + 1, receivedMessages);
  308. }
  309. await c2.DisconnectAsync();
  310. }
  311. [TestMethod]
  312. public async Task MqttServer_NoRetainedMessage()
  313. {
  314. var serverAdapter = new TestMqttServerAdapter();
  315. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  316. var receivedMessagesCount = 0;
  317. try
  318. {
  319. await s.StartAsync(new MqttServerOptions());
  320. var c1 = await serverAdapter.ConnectTestClient("c1");
  321. await c1.PublishAsync(builder => builder.WithTopic("retained").WithPayload(new byte[3]));
  322. await c1.DisconnectAsync();
  323. var c2 = await serverAdapter.ConnectTestClient("c2");
  324. c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  325. await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("retained").Build());
  326. await Task.Delay(500);
  327. }
  328. finally
  329. {
  330. await s.StopAsync();
  331. }
  332. Assert.AreEqual(0, receivedMessagesCount);
  333. }
  334. [TestMethod]
  335. public async Task MqttServer_RetainedMessage()
  336. {
  337. var serverAdapter = new TestMqttServerAdapter();
  338. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  339. var receivedMessagesCount = 0;
  340. try
  341. {
  342. await s.StartAsync(new MqttServerOptions());
  343. var c1 = await serverAdapter.ConnectTestClient("c1");
  344. await c1.PublishAndWaitForAsync(s, new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
  345. await c1.DisconnectAsync();
  346. var c2 = await serverAdapter.ConnectTestClient("c2");
  347. c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  348. await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("retained").Build());
  349. await Task.Delay(500);
  350. }
  351. finally
  352. {
  353. await s.StopAsync();
  354. }
  355. Assert.AreEqual(1, receivedMessagesCount);
  356. }
  357. [TestMethod]
  358. public async Task MqttServer_ClearRetainedMessage()
  359. {
  360. var serverAdapter = new TestMqttServerAdapter();
  361. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  362. var receivedMessagesCount = 0;
  363. try
  364. {
  365. await s.StartAsync(new MqttServerOptions());
  366. var c1 = await serverAdapter.ConnectTestClient("c1");
  367. await c1.PublishAsync(builder => builder.WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag());
  368. await c1.PublishAsync(builder => builder.WithTopic("retained").WithPayload(new byte[0]).WithRetainFlag());
  369. await c1.DisconnectAsync();
  370. var c2 = await serverAdapter.ConnectTestClient("c2");
  371. c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  372. await Task.Delay(200);
  373. await c2.SubscribeAsync(new TopicFilter("retained", MqttQualityOfServiceLevel.AtMostOnce));
  374. await Task.Delay(500);
  375. }
  376. finally
  377. {
  378. await s.StopAsync();
  379. }
  380. Assert.AreEqual(0, receivedMessagesCount);
  381. }
  382. [TestMethod]
  383. public async Task MqttServer_PersistRetainedMessage()
  384. {
  385. var storage = new TestStorage();
  386. var serverAdapter = new TestMqttServerAdapter();
  387. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  388. try
  389. {
  390. var options = new MqttServerOptions { Storage = storage };
  391. await s.StartAsync(options);
  392. var c1 = await serverAdapter.ConnectTestClient("c1");
  393. await c1.PublishAndWaitForAsync(s, new MqttApplicationMessageBuilder().WithTopic("retained").WithPayload(new byte[3]).WithRetainFlag().Build());
  394. await Task.Delay(250);
  395. await c1.DisconnectAsync();
  396. }
  397. finally
  398. {
  399. await s.StopAsync();
  400. }
  401. Assert.AreEqual(1, storage.Messages.Count);
  402. s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  403. var receivedMessagesCount = 0;
  404. try
  405. {
  406. var options = new MqttServerOptions { Storage = storage };
  407. await s.StartAsync(options);
  408. var c2 = await serverAdapter.ConnectTestClient("c2");
  409. c2.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  410. await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("retained").Build());
  411. await Task.Delay(250);
  412. }
  413. finally
  414. {
  415. await s.StopAsync();
  416. }
  417. Assert.AreEqual(1, receivedMessagesCount);
  418. }
  419. [TestMethod]
  420. public async Task MqttServer_InterceptMessage()
  421. {
  422. void Interceptor(MqttApplicationMessageInterceptorContext context)
  423. {
  424. context.ApplicationMessage.Payload = Encoding.ASCII.GetBytes("extended");
  425. }
  426. var serverAdapter = new TestMqttServerAdapter();
  427. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  428. try
  429. {
  430. var options = new MqttServerOptions { ApplicationMessageInterceptor = Interceptor };
  431. await s.StartAsync(options);
  432. var c1 = await serverAdapter.ConnectTestClient("c1");
  433. var c2 = await serverAdapter.ConnectTestClient("c2");
  434. await c2.SubscribeAsync(new TopicFilterBuilder().WithTopic("test").Build());
  435. var isIntercepted = false;
  436. c2.ApplicationMessageReceived += (sender, args) =>
  437. {
  438. isIntercepted = string.Compare("extended", Encoding.UTF8.GetString(args.ApplicationMessage.Payload), StringComparison.Ordinal) == 0;
  439. };
  440. await c1.PublishAsync(builder => builder.WithTopic("test"));
  441. await c1.DisconnectAsync();
  442. await Task.Delay(500);
  443. Assert.IsTrue(isIntercepted);
  444. }
  445. finally
  446. {
  447. await s.StopAsync();
  448. }
  449. }
  450. [TestMethod]
  451. public async Task MqttServer_Body()
  452. {
  453. var serverAdapter = new TestMqttServerAdapter();
  454. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  455. var bodyIsMatching = false;
  456. try
  457. {
  458. await s.StartAsync(new MqttServerOptions());
  459. var c1 = await serverAdapter.ConnectTestClient("c1");
  460. var c2 = await serverAdapter.ConnectTestClient("c2");
  461. c1.ApplicationMessageReceived += (_, e) =>
  462. {
  463. if (Encoding.UTF8.GetString(e.ApplicationMessage.Payload) == "The body")
  464. {
  465. bodyIsMatching = true;
  466. }
  467. };
  468. await c1.SubscribeAsync("A", MqttQualityOfServiceLevel.AtMostOnce);
  469. await c2.PublishAsync(builder => builder.WithTopic("A").WithPayload(Encoding.UTF8.GetBytes("The body")));
  470. await Task.Delay(1000);
  471. }
  472. finally
  473. {
  474. await s.StopAsync();
  475. }
  476. Assert.IsTrue(bodyIsMatching);
  477. }
  478. [TestMethod]
  479. public async Task MqttServer_ConnectionDenied()
  480. {
  481. var server = new MqttFactory().CreateMqttServer();
  482. var client = new MqttFactory().CreateMqttClient();
  483. try
  484. {
  485. var options = new MqttServerOptionsBuilder().WithConnectionValidator(context =>
  486. {
  487. context.ReturnCode = MqttConnectReturnCode.ConnectionRefusedNotAuthorized;
  488. }).Build();
  489. await server.StartAsync(options);
  490. var clientOptions = new MqttClientOptionsBuilder()
  491. .WithTcpServer("localhost").Build();
  492. try
  493. {
  494. await client.ConnectAsync(clientOptions);
  495. Assert.Fail("An exception should be raised.");
  496. }
  497. catch (Exception exception)
  498. {
  499. if (exception is MqttConnectingFailedException)
  500. {
  501. }
  502. else
  503. {
  504. Assert.Fail("Wrong exception.");
  505. }
  506. }
  507. }
  508. finally
  509. {
  510. await client.DisconnectAsync();
  511. await server.StopAsync();
  512. client.Dispose();
  513. }
  514. }
  515. [TestMethod]
  516. public async Task MqttServer_SameClientIdConnectDisconnectEventOrder()
  517. {
  518. var serverAdapter = new MqttTcpServerAdapter(new MqttNetLogger().CreateChildLogger());
  519. var s = new MqttFactory().CreateMqttServer(new[] { serverAdapter }, new MqttNetLogger());
  520. var connectedClient = false;
  521. var connecteCalledBeforeConnectedClients = false;
  522. s.ClientConnected += (_, __) =>
  523. {
  524. connecteCalledBeforeConnectedClients |= connectedClient;
  525. connectedClient = true;
  526. };
  527. s.ClientDisconnected += (_, __) =>
  528. {
  529. connectedClient = false;
  530. };
  531. var clientOptions = new MqttClientOptionsBuilder()
  532. .WithTcpServer("localhost")
  533. .WithClientId(Guid.NewGuid().ToString())
  534. .Build();
  535. await s.StartAsync(new MqttServerOptions());
  536. var c1 = new MqttFactory().CreateMqttClient();
  537. var c2 = new MqttFactory().CreateMqttClient();
  538. await c1.ConnectAsync(clientOptions);
  539. await Task.Delay(100);
  540. await c2.ConnectAsync(clientOptions);
  541. await Task.Delay(100);
  542. await c1.DisconnectAsync();
  543. await c2.DisconnectAsync();
  544. await s.StopAsync();
  545. await Task.Delay(100);
  546. Assert.IsFalse(connecteCalledBeforeConnectedClients, "ClientConnected was called before ClientDisconnect was called");
  547. }
  548. [TestMethod]
  549. public async Task MqttServer_StopAndRestart()
  550. {
  551. var server = new MqttFactory().CreateMqttServer();
  552. await server.StartAsync(new MqttServerOptions());
  553. var client = new MqttFactory().CreateMqttClient();
  554. await client.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());
  555. await server.StopAsync();
  556. try
  557. {
  558. var client2 = new MqttFactory().CreateMqttClient();
  559. await client2.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());
  560. Assert.Fail("Connecting should fail.");
  561. }
  562. catch (Exception)
  563. {
  564. }
  565. await server.StartAsync(new MqttServerOptions());
  566. var client3 = new MqttFactory().CreateMqttClient();
  567. await client3.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());
  568. }
  569. private class TestStorage : IMqttServerStorage
  570. {
  571. public IList<MqttApplicationMessage> Messages = new List<MqttApplicationMessage>();
  572. public Task SaveRetainedMessagesAsync(IList<MqttApplicationMessage> messages)
  573. {
  574. Messages = messages;
  575. return Task.CompletedTask;
  576. }
  577. public Task<IList<MqttApplicationMessage>> LoadRetainedMessagesAsync()
  578. {
  579. return Task.FromResult(Messages);
  580. }
  581. }
  582. private static async Task TestPublishAsync(
  583. string topic,
  584. MqttQualityOfServiceLevel qualityOfServiceLevel,
  585. string topicFilter,
  586. MqttQualityOfServiceLevel filterQualityOfServiceLevel,
  587. int expectedReceivedMessagesCount)
  588. {
  589. var s = new MqttFactory().CreateMqttServer();
  590. var receivedMessagesCount = 0;
  591. try
  592. {
  593. await s.StartAsync(new MqttServerOptions());
  594. var c1 = new MqttFactory().CreateMqttClient();
  595. c1.ApplicationMessageReceived += (_, __) => receivedMessagesCount++;
  596. await c1.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());
  597. await c1.SubscribeAsync(new TopicFilterBuilder().WithTopic(topicFilter).WithQualityOfServiceLevel(filterQualityOfServiceLevel).Build());
  598. var c2 = new MqttFactory().CreateMqttClient();
  599. await c2.ConnectAsync(new MqttClientOptionsBuilder().WithTcpServer("localhost").Build());
  600. await c2.PublishAsync(builder => builder.WithTopic(topic).WithPayload(new byte[0]).WithQualityOfServiceLevel(qualityOfServiceLevel));
  601. await Task.Delay(500);
  602. await c1.UnsubscribeAsync(topicFilter);
  603. await Task.Delay(500);
  604. }
  605. finally
  606. {
  607. await s.StopAsync();
  608. }
  609. Assert.AreEqual(expectedReceivedMessagesCount, receivedMessagesCount);
  610. }
  611. }
  612. }