UService.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Sockets;
  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
  13. /// </summary>
  14. public UService()
  15. {
  16. this.poller = new UPoller();
  17. }
  18. private void Dispose(bool disposing)
  19. {
  20. if (this.poller == null)
  21. {
  22. return;
  23. }
  24. if (disposing)
  25. {
  26. foreach (long id in this.idChannels.Keys.ToArray())
  27. {
  28. UChannel channel = this.idChannels[id];
  29. channel.Dispose();
  30. }
  31. this.poller.Dispose();
  32. }
  33. this.poller = null;
  34. }
  35. public override void Dispose()
  36. {
  37. this.Dispose(true);
  38. }
  39. public override void Add(Action action)
  40. {
  41. this.poller.Add(action);
  42. }
  43. public override AChannel GetChannel(string host, int port)
  44. {
  45. UChannel channel = null;
  46. USocket newSocket = new USocket(this.poller);
  47. channel = new UChannel(newSocket, host, port, this);
  48. newSocket.Disconnect += () => this.OnChannelError(channel.Id, SocketError.SocketError);
  49. this.idChannels[channel.Id] = channel;
  50. return channel;
  51. }
  52. public override AChannel GetChannel(string address)
  53. {
  54. string[] ss = address.Split(':');
  55. int port = int.Parse(ss[1]);
  56. return this.GetChannel(ss[0], port);
  57. }
  58. public override AChannel GetChannel(long id)
  59. {
  60. UChannel channel = null;
  61. this.idChannels.TryGetValue(id, out channel);
  62. return channel;
  63. }
  64. public override void Remove(long id)
  65. {
  66. UChannel channel;
  67. if (!this.idChannels.TryGetValue(id, out channel))
  68. {
  69. return;
  70. }
  71. if (channel == null)
  72. {
  73. return;
  74. }
  75. this.idChannels.Remove(id);
  76. channel.Dispose();
  77. }
  78. public override void Update()
  79. {
  80. this.poller.Update();
  81. }
  82. }
  83. }