TServer.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using Common.Base;
  5. using MongoDB.Bson;
  6. namespace TNet
  7. {
  8. public class TServer: IDisposable
  9. {
  10. private IPoller poller = new TPoller();
  11. private TSocket acceptor;
  12. private readonly Dictionary<string, TSession> sessions = new Dictionary<string, TSession>();
  13. private readonly TimerManager timerManager = new TimerManager();
  14. public TServer(int port)
  15. {
  16. this.acceptor = new TSocket(poller);
  17. this.acceptor.Bind("127.0.0.1", port);
  18. this.acceptor.Listen(100);
  19. }
  20. public void Dispose()
  21. {
  22. if (this.poller == null)
  23. {
  24. return;
  25. }
  26. this.acceptor.Dispose();
  27. this.acceptor = null;
  28. this.poller = null;
  29. }
  30. public void Remove(string address)
  31. {
  32. TSession session;
  33. if (!this.sessions.TryGetValue(address, out session))
  34. {
  35. return;
  36. }
  37. if (session.SendTimer != ObjectId.Empty)
  38. {
  39. this.Timer.Remove(session.SendTimer);
  40. }
  41. if (session.RecvTimer != ObjectId.Empty)
  42. {
  43. this.Timer.Remove(session.RecvTimer);
  44. }
  45. this.sessions.Remove(address);
  46. }
  47. public void Push(Action action)
  48. {
  49. this.poller.Add(action);
  50. }
  51. public async Task<TSession> AcceptAsync()
  52. {
  53. TSocket newSocket = new TSocket(poller);
  54. await this.acceptor.AcceptAsync(newSocket);
  55. TSession session = new TSession(newSocket, this);
  56. sessions[newSocket.RemoteAddress] = session;
  57. return session;
  58. }
  59. public async Task<TSession> ConnectAsync(string host, int port)
  60. {
  61. TSocket newSocket = new TSocket(poller);
  62. await newSocket.ConnectAsync(host, port);
  63. TSession session = new TSession(newSocket, this);
  64. sessions[newSocket.RemoteAddress] = session;
  65. return session;
  66. }
  67. public TSession Get(string host, int port)
  68. {
  69. TSession session = null;
  70. this.sessions.TryGetValue(host + ":" + port, out session);
  71. return session;
  72. }
  73. public async Task<TSession> GetOrCreate(string host, int port)
  74. {
  75. TSession session = null;
  76. if (this.sessions.TryGetValue(host + ":" + port, out session))
  77. {
  78. return session;
  79. }
  80. return await ConnectAsync(host, port);
  81. }
  82. public void Start()
  83. {
  84. while (true)
  85. {
  86. poller.Run(1);
  87. this.timerManager.Refresh();
  88. }
  89. }
  90. public TimerManager Timer
  91. {
  92. get
  93. {
  94. return this.timerManager;
  95. }
  96. }
  97. }
  98. }