TServiceTest.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 async void ClientEvent(IService service, string hostName, ushort port)
  16. {
  17. AChannel channel = await service.GetChannel(hostName, port);
  18. for (int i = 0; i < echoTimes; ++i)
  19. {
  20. channel.SendAsync("0123456789".ToByteArray());
  21. byte[] bytes = await channel.RecvAsync();
  22. CollectionAssert.AreEqual("9876543210".ToByteArray(), bytes);
  23. }
  24. this.barrier.RemoveParticipant();
  25. }
  26. private async void ServerEvent(IService service)
  27. {
  28. AChannel channel = await service.GetChannel();
  29. for (int i = 0; i < echoTimes; ++i)
  30. {
  31. byte[] bytes = await channel.RecvAsync();
  32. CollectionAssert.AreEqual("0123456789".ToByteArray(), bytes);
  33. Array.Reverse(bytes);
  34. channel.SendAsync(bytes);
  35. }
  36. this.barrier.RemoveParticipant();
  37. }
  38. [Test]
  39. public void ClientSendToServer()
  40. {
  41. const string hostName = "127.0.0.1";
  42. const ushort port = 8889;
  43. using(IService clientService = new TService())
  44. using (IService serverService = new TService(hostName, 8889))
  45. {
  46. Task task1 = Task.Factory.StartNew(() => clientService.Start(), TaskCreationOptions.LongRunning);
  47. Task task2 = Task.Factory.StartNew(() => serverService.Start(), TaskCreationOptions.LongRunning);
  48. // 往server host线程增加事件,accept
  49. serverService.Add(() => this.ServerEvent(serverService));
  50. Thread.Sleep(1000);
  51. // 往client host线程增加事件,client线程连接server
  52. clientService.Add(() => this.ClientEvent(clientService, hostName, port));
  53. this.barrier.SignalAndWait();
  54. serverService.Add(serverService.Stop);
  55. clientService.Add(clientService.Stop);
  56. Task.WaitAll(task1, task2);
  57. }
  58. }
  59. }
  60. }