TService.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 TService: AService
  8. {
  9. private TPoller poller = new TPoller();
  10. private readonly TSocket acceptor;
  11. private readonly Dictionary<long, TChannel> idChannels = new Dictionary<long, TChannel>();
  12. /// <summary>
  13. /// 即可做client也可做server
  14. /// </summary>
  15. /// <param name="host"></param>
  16. /// <param name="port"></param>
  17. public TService(string host, int port)
  18. {
  19. this.acceptor = new TSocket(this.poller, host, port);
  20. }
  21. public TService()
  22. {
  23. }
  24. public override void Dispose()
  25. {
  26. if (this.poller == null)
  27. {
  28. return;
  29. }
  30. foreach (long id in this.idChannels.Keys.ToArray())
  31. {
  32. TChannel channel = this.idChannels[id];
  33. channel.Dispose();
  34. }
  35. this.acceptor?.Dispose();
  36. this.poller = null;
  37. }
  38. public override void Add(Action action)
  39. {
  40. this.poller.Add(action);
  41. }
  42. public override AChannel GetChannel(long id)
  43. {
  44. TChannel channel = null;
  45. this.idChannels.TryGetValue(id, out channel);
  46. return channel;
  47. }
  48. public override async Task<AChannel> AcceptChannel()
  49. {
  50. if (this.acceptor == null)
  51. {
  52. throw new Exception("service construct must use host and port param");
  53. }
  54. TSocket socket = new TSocket(this.poller);
  55. await this.acceptor.AcceptAsync(socket);
  56. TChannel channel = new TChannel(socket, this);
  57. this.idChannels[channel.Id] = channel;
  58. return channel;
  59. }
  60. public override AChannel ConnectChannel(string host, int port)
  61. {
  62. TSocket newSocket = new TSocket(this.poller);
  63. TChannel channel = new TChannel(newSocket, host, port, this);
  64. this.idChannels[channel.Id] = channel;
  65. return channel;
  66. }
  67. public override void Remove(long id)
  68. {
  69. TChannel channel;
  70. if (!this.idChannels.TryGetValue(id, out channel))
  71. {
  72. return;
  73. }
  74. if (channel == null)
  75. {
  76. return;
  77. }
  78. this.idChannels.Remove(id);
  79. channel.Dispose();
  80. }
  81. public override void Update()
  82. {
  83. this.poller.Update();
  84. }
  85. }
  86. }