UServiceTest.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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 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. channel.SendAsync("0123456789".ToByteArray());
  19. byte[] bytes = await channel.RecvAsync();
  20. CollectionAssert.AreEqual("9876543210".ToByteArray(), bytes);
  21. this.barrier.RemoveParticipant();
  22. }
  23. private async void ServerEvent(IService service)
  24. {
  25. AChannel channel = await service.GetChannel();
  26. byte[] bytes = await channel.RecvAsync();
  27. CollectionAssert.AreEqual("0123456789".ToByteArray(), bytes);
  28. Array.Reverse(bytes);
  29. channel.SendAsync(bytes);
  30. this.barrier.RemoveParticipant();
  31. }
  32. [Test]
  33. public void ClientSendToServer()
  34. {
  35. const string hostName = "127.0.0.1";
  36. const ushort port = 8889;
  37. IService clientService = new UService(hostName, 8888);
  38. IService serverService = new UService(hostName, 8889);
  39. Task.Factory.StartNew(() => clientService.Run(), TaskCreationOptions.LongRunning);
  40. Task.Factory.StartNew(() => serverService.Run(), TaskCreationOptions.LongRunning);
  41. // 往server host线程增加事件,accept
  42. serverService.Add(() => this.ServerEvent(serverService));
  43. Thread.Sleep(1000);
  44. // 往client host线程增加事件,client线程连接server
  45. clientService.Add(() => this.ClientEvent(clientService, hostName, port));
  46. this.barrier.SignalAndWait();
  47. }
  48. }
  49. }