NetworkComponent.cs 1.9 KB

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