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.
 
 
 
 

76 lines
2.4 KiB

  1. using Microsoft.VisualStudio.TestTools.UnitTesting;
  2. using MQTTnet.Implementations;
  3. using System;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace MQTTnet.Tests
  9. {
  10. [TestClass]
  11. public class MqttTcpChannel_Tests
  12. {
  13. [TestMethod]
  14. public async Task Dispose_Channel_While_Used()
  15. {
  16. var ct = new CancellationTokenSource();
  17. var serverSocket = new CrossPlatformSocket(AddressFamily.InterNetwork);
  18. try
  19. {
  20. serverSocket.Bind(new IPEndPoint(IPAddress.Any, 50001));
  21. serverSocket.Listen(0);
  22. #pragma warning disable 4014
  23. Task.Run(async () =>
  24. #pragma warning restore 4014
  25. {
  26. while (!ct.IsCancellationRequested)
  27. {
  28. var client = await serverSocket.AcceptAsync();
  29. var data = new byte[] { 128 };
  30. await client.SendAsync(new ArraySegment<byte>(data), SocketFlags.None);
  31. }
  32. }, ct.Token);
  33. var clientSocket = new CrossPlatformSocket(AddressFamily.InterNetwork);
  34. await clientSocket.ConnectAsync("localhost", 50001, CancellationToken.None);
  35. var tcpChannel = new MqttTcpChannel(clientSocket.GetStream(), "test", null);
  36. await Task.Delay(100, ct.Token);
  37. var buffer = new byte[1];
  38. await tcpChannel.ReadAsync(buffer, 0, 1, ct.Token);
  39. Assert.AreEqual(128, buffer[0]);
  40. // This block should fail after dispose.
  41. #pragma warning disable 4014
  42. Task.Run(() =>
  43. #pragma warning restore 4014
  44. {
  45. Task.Delay(200, ct.Token);
  46. tcpChannel.Dispose();
  47. }, ct.Token);
  48. try
  49. {
  50. await tcpChannel.ReadAsync(buffer, 0, 1, CancellationToken.None);
  51. }
  52. catch (Exception exception)
  53. {
  54. Assert.IsInstanceOfType(exception, typeof(SocketException));
  55. Assert.AreEqual(SocketError.OperationAborted, ((SocketException)exception).SocketErrorCode);
  56. }
  57. }
  58. finally
  59. {
  60. ct.Cancel(false);
  61. serverSocket.Dispose();
  62. }
  63. }
  64. }
  65. }