UServiceTest.cs 2.2 KB

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