UServiceTest.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 UNet;
  8. namespace UNetTest
  9. {
  10. [TestFixture]
  11. public class UServiceTest
  12. {
  13. private const int echoTimes = 10000;
  14. private readonly Barrier barrier = new Barrier(2);
  15. private bool isClientStop;
  16. private bool isServerStop;
  17. private async void ClientEvent(IService clientService, string hostName, ushort port)
  18. {
  19. AChannel channel = await clientService.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. }
  39. [Test]
  40. public void ClientSendToServer()
  41. {
  42. const string hostName = "127.0.0.1";
  43. const ushort port = 8889;
  44. using (IService clientService = new UService(hostName, 8888))
  45. {
  46. using (IService serverService = new UService(hostName, 8889))
  47. {
  48. Task task1 = Task.Factory.StartNew(() =>
  49. {
  50. while (!this.isClientStop)
  51. {
  52. clientService.Update();
  53. }
  54. }, TaskCreationOptions.LongRunning);
  55. Task task2 = Task.Factory.StartNew(() =>
  56. {
  57. while (!this.isServerStop)
  58. {
  59. serverService.Update();
  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. this.barrier.SignalAndWait();
  68. serverService.Add(() => { this.isServerStop = true; });
  69. clientService.Add(() => { this.isClientStop = true; });
  70. Task.WaitAll(task1, task2);
  71. }
  72. }
  73. }
  74. }
  75. }