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.
 
 
 
 

77 lines
2.7 KiB

  1. using System;
  2. using System.Net.Sockets;
  3. using System.Text;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;
  7. using MQTTnet.Implementations;
  8. using MQTTnet.Server;
  9. namespace MQTTnet.Tests.Server
  10. {
  11. [TestClass]
  12. public sealed class Connection_Tests : BaseTestClass
  13. {
  14. [TestMethod]
  15. public async Task Close_Idle_Connection_On_Connect()
  16. {
  17. using (var testEnvironment = CreateTestEnvironment())
  18. {
  19. await testEnvironment.StartServer(new MqttServerOptionsBuilder().WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(1)));
  20. var client = new CrossPlatformSocket(AddressFamily.InterNetwork);
  21. await client.ConnectAsync("localhost", testEnvironment.ServerPort, CancellationToken.None);
  22. // Don't send anything. The server should close the connection.
  23. await Task.Delay(TimeSpan.FromSeconds(3));
  24. try
  25. {
  26. var receivedBytes = await client.ReceiveAsync(new ArraySegment<byte>(new byte[10]), SocketFlags.Partial);
  27. if (receivedBytes == 0)
  28. {
  29. return;
  30. }
  31. Assert.Fail("Receive should throw an exception.");
  32. }
  33. catch (SocketException)
  34. {
  35. }
  36. }
  37. }
  38. [TestMethod]
  39. public async Task Send_Garbage()
  40. {
  41. using (var testEnvironment = CreateTestEnvironment())
  42. {
  43. await testEnvironment.StartServer(new MqttServerOptionsBuilder().WithDefaultCommunicationTimeout(TimeSpan.FromSeconds(1)));
  44. // Send an invalid packet and ensure that the server will close the connection and stay in a waiting state
  45. // forever. This is security related.
  46. var client = new CrossPlatformSocket(AddressFamily.InterNetwork);
  47. await client.ConnectAsync("localhost", testEnvironment.ServerPort, CancellationToken.None);
  48. var buffer = Encoding.UTF8.GetBytes("Garbage");
  49. await client.SendAsync(new ArraySegment<byte>(buffer), SocketFlags.None);
  50. await Task.Delay(TimeSpan.FromSeconds(3));
  51. try
  52. {
  53. var receivedBytes = await client.ReceiveAsync(new ArraySegment<byte>(new byte[10]), SocketFlags.Partial);
  54. if (receivedBytes == 0)
  55. {
  56. return;
  57. }
  58. Assert.Fail("Receive should throw an exception.");
  59. }
  60. catch (SocketException)
  61. {
  62. }
  63. }
  64. }
  65. }
  66. }