NetInnerComponent.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System.Collections.Generic;
  2. using System.Threading.Tasks;
  3. using Base;
  4. namespace Model
  5. {
  6. [ObjectEvent]
  7. public class NetInnerComponentEvent : ObjectEvent<NetInnerComponent>, IUpdate, IAwake, IAwake<string, int>
  8. {
  9. public void Update()
  10. {
  11. NetworkComponent component = this.GetValue();
  12. component.Update();
  13. }
  14. public void Awake()
  15. {
  16. this.GetValue().Awake();
  17. }
  18. public void Awake(string host, int port)
  19. {
  20. this.GetValue().Awake(host, port);
  21. }
  22. }
  23. public class NetInnerComponent : NetworkComponent
  24. {
  25. private readonly Dictionary<string, Session> adressSessions = new Dictionary<string, Session>();
  26. public void Awake()
  27. {
  28. this.Awake(NetworkProtocol.TCP);
  29. }
  30. public void Awake(string host, int port)
  31. {
  32. this.Awake(NetworkProtocol.TCP, host, port);
  33. }
  34. protected override async Task<Session> Accept()
  35. {
  36. Session session = await base.Accept();
  37. this.AddToAddressDict(session);
  38. return session;
  39. }
  40. private void AddToAddressDict(Session session)
  41. {
  42. Session s;
  43. if (this.adressSessions.TryGetValue(session.RemoteAddress, out s))
  44. {
  45. this.Remove(s.Id);
  46. Log.Warning($"session 地址冲突, 可能是客户端断开, 服务器还没检测到!: {session.RemoteAddress}");
  47. }
  48. this.adressSessions.Add(session.RemoteAddress, session);
  49. }
  50. public override void Remove(long id)
  51. {
  52. Session session = this.Get(id);
  53. if (session == null)
  54. {
  55. return;
  56. }
  57. this.adressSessions.Remove(session.RemoteAddress);
  58. base.Remove(id);
  59. }
  60. /// <summary>
  61. /// 从地址缓存中取Session,如果没有则创建一个新的Session,并且保存到地址缓存中
  62. /// </summary>
  63. public Session Get(string address)
  64. {
  65. Session session;
  66. if (this.adressSessions.TryGetValue(address, out session))
  67. {
  68. return session;
  69. }
  70. session = this.Create(address);
  71. this.AddToAddressDict(session);
  72. return session;
  73. }
  74. }
  75. }