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 System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Microsoft.VisualStudio.TestTools.UnitTesting;
  7. using MQTTnet.Implementations;
  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 Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  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 Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  34. await clientSocket.ConnectAsync(IPAddress.Loopback, 50001);
  35. await Task.Delay(100, ct.Token);
  36. var tcpChannel = new MqttTcpChannel(new NetworkStream(clientSocket, true), "test");
  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. }