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.
 
 
 
 

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