NetworkComponent.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Net.Sockets;
  3. namespace Base
  4. {
  5. [ObjectEvent]
  6. public class NetworkComponentEvent : ObjectEvent<NetworkComponent>, IUpdate, IAwake<NetworkProtocol, string, int>
  7. {
  8. public void Update()
  9. {
  10. NetworkComponent component = this.GetValue();
  11. component.Update();
  12. }
  13. public void Awake(NetworkProtocol protocol, string host, int port)
  14. {
  15. this.GetValue().Awake(protocol, host, port);
  16. }
  17. }
  18. public class NetworkComponent: Component
  19. {
  20. public 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, string host, int port)
  43. {
  44. switch (protocol)
  45. {
  46. case NetworkProtocol.TCP:
  47. this.Service = new TService(host, port) { OnError = this.OnError };
  48. break;
  49. case NetworkProtocol.UDP:
  50. this.Service = new UService(host, port) { 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 void OnError(long id, SocketError error)
  65. {
  66. Env env = new Env();
  67. env[EnvBaseKey.ChannelError] = error;
  68. Game.Scene.GetComponent<EventComponent>().Run(EventBaseType.NetworkChannelError, env);
  69. }
  70. }
  71. }