UServiceTest.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Common.Helper;
  5. using Common.Logger;
  6. using UNet;
  7. using Microsoft.VisualStudio.TestTools.UnitTesting;
  8. using Network;
  9. using TNet;
  10. namespace UNetTest
  11. {
  12. [TestClass]
  13. public class UServiceTest
  14. {
  15. private readonly Barrier barrier = new Barrier(3);
  16. private async void ClientEvent(IService service, string hostName, ushort port)
  17. {
  18. IChannel channel = await service.GetChannel(hostName, port);
  19. channel.SendAsync("0123456789".ToByteArray());
  20. byte[] bytes = await channel.RecvAsync();
  21. CollectionAssert.AreEqual("9876543210".ToByteArray(), bytes);
  22. barrier.RemoveParticipant();
  23. }
  24. private async void ServerEvent(IService service)
  25. {
  26. IChannel channel = await service.GetChannel();
  27. byte[] bytes = await channel.RecvAsync();
  28. CollectionAssert.AreEqual("0123456789".ToByteArray(), bytes);
  29. Array.Reverse(bytes);
  30. channel.SendAsync(bytes);
  31. barrier.RemoveParticipant();
  32. }
  33. [TestMethod]
  34. public void ClientSendToServer()
  35. {
  36. const string hostName = "127.0.0.1";
  37. const ushort port = 8889;
  38. IService clientService = new UService();
  39. IService serverService = new UService(hostName, 8889);
  40. Task.Factory.StartNew(() => clientService.Run(), TaskCreationOptions.LongRunning);
  41. Task.Factory.StartNew(() => serverService.Run(), TaskCreationOptions.LongRunning);
  42. // 往server host线程增加事件,accept
  43. serverService.Add(() => ServerEvent(serverService));
  44. Thread.Sleep(1000);
  45. // 往client host线程增加事件,client线程连接server
  46. clientService.Add(() => ClientEvent(clientService, hostName, port));
  47. barrier.SignalAndWait();
  48. }
  49. }
  50. }