You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

65 lines
2.7 KiB

  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using MQTTnet.Formatter;
  6. using MQTTnet.Packets;
  7. using MQTTnet.Protocol;
  8. using MQTTnet.Tests.Mockups;
  9. namespace MQTTnet.Tests
  10. {
  11. [TestClass]
  12. public sealed class Server_KeepAlive_Tests
  13. {
  14. [TestMethod]
  15. public async Task Disconnect_Client_DueTo_KeepAlive()
  16. {
  17. using (var testEnvironment = new TestEnvironment())
  18. {
  19. await testEnvironment.StartServerAsync();
  20. var client = await testEnvironment.ConnectLowLevelClientAsync(o => o
  21. .WithCommunicationTimeout(TimeSpan.FromSeconds(1))
  22. .WithCommunicationTimeout(TimeSpan.Zero)
  23. .WithProtocolVersion(MqttProtocolVersion.V500)).ConfigureAwait(false);
  24. await client.SendAsync(new MqttConnectPacket
  25. {
  26. CleanSession = true,
  27. ClientId = "abc",
  28. KeepAlivePeriod = 1
  29. }, CancellationToken.None).ConfigureAwait(false);
  30. var responsePacket = await client.ReceiveAsync(CancellationToken.None).ConfigureAwait(false);
  31. Assert.IsTrue(responsePacket is MqttConnAckPacket);
  32. for (var i = 0; i < 6; i++)
  33. {
  34. await Task.Delay(500);
  35. await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
  36. responsePacket = await client.ReceiveAsync(CancellationToken.None);
  37. Assert.IsTrue(responsePacket is MqttPingRespPacket);
  38. }
  39. // If we reach this point everything works as expected (server did not close the connection
  40. // due to proper ping messages.
  41. // Now we will wait 1.1 seconds because the server MUST wait 1.5 seconds in total (See spec).
  42. await Task.Delay(1100);
  43. await client.SendAsync(MqttPingReqPacket.Instance, CancellationToken.None);
  44. responsePacket = await client.ReceiveAsync(CancellationToken.None);
  45. Assert.IsTrue(responsePacket is MqttPingRespPacket);
  46. // Now we will wait longer than 1.5 so that the server will close the connection.
  47. responsePacket = await client.ReceiveAsync(CancellationToken.None);
  48. var disconnectPacket = responsePacket as MqttDisconnectPacket;
  49. Assert.IsTrue(disconnectPacket != null);
  50. Assert.AreEqual(disconnectPacket.ReasonCode, MqttDisconnectReasonCode.KeepAliveTimeout);
  51. }
  52. }
  53. }
  54. }