TService.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Base
  5. {
  6. public sealed class TService: AService
  7. {
  8. private TPoller poller = new TPoller();
  9. private readonly Dictionary<long, TChannel> idChannels = new Dictionary<long, TChannel>();
  10. private void Dispose(bool disposing)
  11. {
  12. if (this.poller == null)
  13. {
  14. return;
  15. }
  16. if (disposing)
  17. {
  18. foreach (long id in this.idChannels.Keys.ToArray())
  19. {
  20. TChannel channel = this.idChannels[id];
  21. channel.Dispose();
  22. }
  23. }
  24. this.poller = null;
  25. }
  26. public override void Dispose()
  27. {
  28. this.Dispose(true);
  29. }
  30. public override void Add(Action action)
  31. {
  32. this.poller.Add(action);
  33. }
  34. public override AChannel GetChannel(long id)
  35. {
  36. TChannel channel = null;
  37. this.idChannels.TryGetValue(id, out channel);
  38. return channel;
  39. }
  40. public override void Remove(long id)
  41. {
  42. TChannel channel;
  43. if (!this.idChannels.TryGetValue(id, out channel))
  44. {
  45. return;
  46. }
  47. if (channel == null)
  48. {
  49. return;
  50. }
  51. this.idChannels.Remove(id);
  52. channel.Dispose();
  53. }
  54. public override AChannel GetChannel(string host, int port)
  55. {
  56. TChannel channel = null;
  57. TSocket newSocket = new TSocket(this.poller);
  58. channel = new TChannel(newSocket, host, port, this);
  59. channel.OnError += this.OnChannelError;
  60. this.idChannels[channel.Id] = channel;
  61. return channel;
  62. }
  63. public override AChannel GetChannel(string address)
  64. {
  65. string[] ss = address.Split(':');
  66. int port = int.Parse(ss[1]);
  67. return this.GetChannel(ss[0], port);
  68. }
  69. public override void Update()
  70. {
  71. this.poller.Update();
  72. }
  73. }
  74. }