NetworkComponent.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using System.Net.Sockets;
  3. using Base;
  4. namespace Model
  5. {
  6. [ObjectEvent]
  7. public class NetworkComponentEvent : ObjectEvent<NetworkComponent>, IUpdate, IAwake<NetworkProtocol>
  8. {
  9. public void Update()
  10. {
  11. NetworkComponent component = this.GetValue();
  12. component.Update();
  13. }
  14. public void Awake(NetworkProtocol protocol)
  15. {
  16. this.GetValue().Awake(protocol);
  17. }
  18. }
  19. public class NetworkComponent: Component
  20. {
  21. private AService service;
  22. private void Dispose(bool disposing)
  23. {
  24. if (this.service == null)
  25. {
  26. return;
  27. }
  28. base.Dispose();
  29. if (disposing)
  30. {
  31. this.service.Dispose();
  32. }
  33. this.service = null;
  34. }
  35. public override void Dispose()
  36. {
  37. if (this.Id == 0)
  38. {
  39. return;
  40. }
  41. this.Dispose(true);
  42. }
  43. public void Awake(NetworkProtocol protocol)
  44. {
  45. switch (protocol)
  46. {
  47. case NetworkProtocol.TCP:
  48. this.service = new TService { OnError = this.OnError };
  49. break;
  50. case NetworkProtocol.UDP:
  51. this.service = new UService { OnError = this.OnError };
  52. break;
  53. default:
  54. throw new ArgumentOutOfRangeException();
  55. }
  56. }
  57. public void Update()
  58. {
  59. if (this.service == null)
  60. {
  61. return;
  62. }
  63. this.service.Update();
  64. }
  65. public AChannel GetChannel(long channelId)
  66. {
  67. AChannel channel = this.service?.GetChannel(channelId);
  68. return channel;
  69. }
  70. public AChannel ConnectChannel(string host, int port)
  71. {
  72. AChannel channel = this.service.GetChannel(host, port);
  73. return channel;
  74. }
  75. public void OnError(long id, SocketError error)
  76. {
  77. Env env = new Env();
  78. env[EnvBaseKey.ChannelError] = error;
  79. Game.Scene.GetComponent<EventComponent>().Run(EventBaseType.NetworkChannelError, env);
  80. }
  81. public void RemoveChannel(long channelId)
  82. {
  83. AChannel channel = this.service?.GetChannel(channelId);
  84. if (channel == null)
  85. {
  86. return;
  87. }
  88. this.service.Remove(channelId);
  89. channel.Dispose();
  90. }
  91. }
  92. }