TService.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading.Tasks;
  7. namespace Model
  8. {
  9. public sealed class TService: AService
  10. {
  11. private TcpListener acceptor;
  12. private readonly Dictionary<long, TChannel> idChannels = new Dictionary<long, TChannel>();
  13. /// <summary>
  14. /// 即可做client也可做server
  15. /// </summary>
  16. /// <param name="host"></param>
  17. /// <param name="port"></param>
  18. public TService(string host, int port)
  19. {
  20. this.acceptor = new TcpListener(new IPEndPoint(IPAddress.Parse(host), port));
  21. this.acceptor.Start();
  22. }
  23. public TService()
  24. {
  25. }
  26. public override void Dispose()
  27. {
  28. if (this.acceptor == null)
  29. {
  30. return;
  31. }
  32. foreach (long id in this.idChannels.Keys.ToArray())
  33. {
  34. TChannel channel = this.idChannels[id];
  35. channel.Dispose();
  36. }
  37. this.acceptor.Stop();
  38. this.acceptor = null;
  39. }
  40. public override void Add(Action action)
  41. {
  42. }
  43. public override AChannel GetChannel(long id)
  44. {
  45. TChannel channel = null;
  46. this.idChannels.TryGetValue(id, out channel);
  47. return channel;
  48. }
  49. public override async Task<AChannel> AcceptChannel()
  50. {
  51. if (this.acceptor == null)
  52. {
  53. throw new Exception("service construct must use host and port param");
  54. }
  55. TcpClient tcpClient = await this.acceptor.AcceptTcpClientAsync();
  56. TChannel channel = new TChannel(tcpClient, this);
  57. this.idChannels[channel.Id] = channel;
  58. return channel;
  59. }
  60. public override AChannel ConnectChannel(string host, int port)
  61. {
  62. TcpClient tcpClient = new TcpClient();
  63. TChannel channel = new TChannel(tcpClient, 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. }
  84. }
  85. }