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.
 
 
 
 

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