TServiceTest.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Common.Helper;
  5. using Common.Network;
  6. using NUnit.Framework;
  7. using TNet;
  8. namespace TNetTest
  9. {
  10. [TestFixture]
  11. public class TServiceTest
  12. {
  13. private const int echoTimes = 10000;
  14. private readonly Barrier barrier = new Barrier(3);
  15. private bool isClientStop;
  16. private bool isServerStop;
  17. private async void ClientEvent(IService service, string hostName, ushort port)
  18. {
  19. AChannel channel = await service.GetChannel(hostName, port);
  20. for (int i = 0; i < echoTimes; ++i)
  21. {
  22. channel.SendAsync("0123456789".ToByteArray());
  23. byte[] bytes = await channel.RecvAsync();
  24. CollectionAssert.AreEqual("9876543210".ToByteArray(), bytes);
  25. }
  26. this.barrier.RemoveParticipant();
  27. }
  28. private async void ServerEvent(IService service)
  29. {
  30. AChannel channel = await service.GetChannel();
  31. for (int i = 0; i < echoTimes; ++i)
  32. {
  33. byte[] bytes = await channel.RecvAsync();
  34. CollectionAssert.AreEqual("0123456789".ToByteArray(), bytes);
  35. Array.Reverse(bytes);
  36. channel.SendAsync(bytes);
  37. }
  38. this.barrier.RemoveParticipant();
  39. }
  40. [Test]
  41. public void ClientSendToServer()
  42. {
  43. const string hostName = "127.0.0.1";
  44. const ushort port = 8889;
  45. using (IService clientService = new TService())
  46. {
  47. using (IService serverService = new TService(hostName, 8889))
  48. {
  49. Task task1 = Task.Factory.StartNew(() =>
  50. {
  51. while (!this.isClientStop)
  52. {
  53. clientService.Update();
  54. }
  55. }, TaskCreationOptions.LongRunning);
  56. Task task2 = Task.Factory.StartNew(() =>
  57. {
  58. while (!this.isServerStop)
  59. {
  60. serverService.Update();
  61. }
  62. }, TaskCreationOptions.LongRunning);
  63. // 往server host线程增加事件,accept
  64. serverService.Add(() => this.ServerEvent(serverService));
  65. Thread.Sleep(1000);
  66. // 往client host线程增加事件,client线程连接server
  67. clientService.Add(() => this.ClientEvent(clientService, hostName, port));
  68. this.barrier.SignalAndWait();
  69. serverService.Add(() => { this.isServerStop = true; });
  70. clientService.Add(() => { this.isClientStop = true; });
  71. Task.WaitAll(task1, task2);
  72. }
  73. }
  74. }
  75. }
  76. }