UServiceTest.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 async void ClientEvent(IService clientService, string hostName, ushort port)
  17. {
  18. AChannel channel = await clientService.GetChannel(hostName, port);
  19. for (int i = 0; i < echoTimes; ++i)
  20. {
  21. channel.SendAsync("0123456789".ToByteArray());
  22. byte[] bytes = await channel.RecvAsync();
  23. CollectionAssert.AreEqual("9876543210".ToByteArray(), bytes);
  24. }
  25. barrier.RemoveParticipant();
  26. }
  27. private async void ServerEvent(IService service)
  28. {
  29. AChannel channel = await service.GetChannel();
  30. for (int i = 0; i < echoTimes; ++i)
  31. {
  32. byte[] bytes = await channel.RecvAsync();
  33. CollectionAssert.AreEqual("0123456789".ToByteArray(), bytes);
  34. Array.Reverse(bytes);
  35. channel.SendAsync(bytes);
  36. }
  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 UService(hostName, 8888))
  44. using (IService serverService = new UService(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. barrier.SignalAndWait();
  54. serverService.Add(serverService.Stop);
  55. clientService.Add(clientService.Stop);
  56. Task.WaitAll(task1, task2);
  57. }
  58. }
  59. }
  60. }