UService.cs 2.4 KB

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