UService.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Network;
  5. namespace UNet
  6. {
  7. public sealed class UService: IService
  8. {
  9. private UPoller poller;
  10. private readonly Dictionary<string, UChannel> channels = new Dictionary<string, UChannel>();
  11. /// <summary>
  12. /// 即可做client也可做server
  13. /// </summary>
  14. /// <param name="host"></param>
  15. /// <param name="port"></param>
  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. private void Dispose(bool disposing)
  28. {
  29. if (this.poller == null)
  30. {
  31. return;
  32. }
  33. if (disposing)
  34. {
  35. this.poller.Dispose();
  36. }
  37. this.poller = null;
  38. }
  39. ~UService()
  40. {
  41. Dispose(false);
  42. }
  43. public void Dispose()
  44. {
  45. Dispose(true);
  46. GC.SuppressFinalize(this);
  47. }
  48. public void Add(Action action)
  49. {
  50. this.poller.Add(action);
  51. }
  52. private async Task<IChannel> ConnectAsync(string host, int port)
  53. {
  54. USocket newSocket = await this.poller.ConnectAsync(host, (ushort)port);
  55. UChannel channel = new UChannel(newSocket, this);
  56. channels[channel.RemoteAddress] = channel;
  57. return channel;
  58. }
  59. public async Task<IChannel> GetChannel(string address)
  60. {
  61. string[] ss = address.Split(':');
  62. int port = Convert.ToInt32(ss[1]);
  63. return await GetChannel(ss[0], port);
  64. }
  65. public async Task<IChannel> GetChannel(string host, int port)
  66. {
  67. UChannel channel = null;
  68. if (this.channels.TryGetValue(host + ":" + port, out channel))
  69. {
  70. return channel;
  71. }
  72. return await ConnectAsync(host, port);
  73. }
  74. public async Task<IChannel> GetChannel()
  75. {
  76. USocket socket = await this.poller.AcceptAsync();
  77. UChannel channel = new UChannel(socket, this);
  78. channels[channel.RemoteAddress] = channel;
  79. return channel;
  80. }
  81. public void Remove(IChannel channel)
  82. {
  83. UChannel tChannel = channel as UChannel;
  84. if (tChannel == null)
  85. {
  86. return;
  87. }
  88. this.channels.Remove(channel.RemoteAddress);
  89. }
  90. public void RunOnce(int timeout)
  91. {
  92. this.poller.RunOnce(timeout);
  93. }
  94. public void Run()
  95. {
  96. this.poller.Run();
  97. }
  98. }
  99. }