UServiceTest.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. namespace UNetTest
  10. {
  11. [TestClass]
  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. IChannel channel = await service.GetChannel(hostName, port);
  18. channel.SendAsync("0123456789".ToByteArray());
  19. byte[] bytes = await channel.RecvAsync();
  20. CollectionAssert.AreEqual("9876543210".ToByteArray(), bytes);
  21. barrier.RemoveParticipant();
  22. }
  23. private async void ServerEvent(IService service)
  24. {
  25. IChannel 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. barrier.RemoveParticipant();
  31. }
  32. [TestMethod]
  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(() => ServerEvent(serverService));
  43. Thread.Sleep(1000);
  44. // 往client host线程增加事件,client线程连接server
  45. clientService.Add(() => ClientEvent(clientService, hostName, port));
  46. barrier.SignalAndWait();
  47. }
  48. }
  49. }