UService.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. namespace Base
  6. {
  7. public sealed class UService: AService
  8. {
  9. private UPoller poller;
  10. private readonly Dictionary<long, UChannel> idChannels = new Dictionary<long, UChannel>();
  11. /// <summary>
  12. /// 即可做client也可做server
  13. /// </summary>
  14. public UService(string host, int port)
  15. {
  16. this.poller = new UPoller(host, (ushort)port);
  17. }
  18. /// <summary>
  19. /// 只能做client
  20. /// </summary>
  21. public UService()
  22. {
  23. this.poller = new UPoller();
  24. }
  25. public override void Dispose()
  26. {
  27. if (this.poller == null)
  28. {
  29. return;
  30. }
  31. foreach (long id in this.idChannels.Keys.ToArray())
  32. {
  33. UChannel channel = this.idChannels[id];
  34. channel.Dispose();
  35. }
  36. this.poller = null;
  37. }
  38. public override void Add(Action action)
  39. {
  40. this.poller.Add(action);
  41. }
  42. public override async Task<AChannel> AcceptChannel()
  43. {
  44. USocket socket = await this.poller.AcceptAsync();
  45. UChannel channel = new UChannel(socket, this);
  46. this.idChannels[channel.Id] = channel;
  47. return channel;
  48. }
  49. public override AChannel ConnectChannel(string host, int port)
  50. {
  51. USocket newSocket = new USocket(this.poller);
  52. UChannel channel = new UChannel(newSocket, host, port, this);
  53. this.idChannels[channel.Id] = channel;
  54. return channel;
  55. }
  56. public override AChannel GetChannel(long id)
  57. {
  58. UChannel channel = null;
  59. this.idChannels.TryGetValue(id, out channel);
  60. return channel;
  61. }
  62. public override void Remove(long id)
  63. {
  64. UChannel channel;
  65. if (!this.idChannels.TryGetValue(id, out channel))
  66. {
  67. return;
  68. }
  69. if (channel == null)
  70. {
  71. return;
  72. }
  73. this.idChannels.Remove(id);
  74. channel.Dispose();
  75. }
  76. public override void Update()
  77. {
  78. this.poller.Update();
  79. }
  80. }
  81. }