AppManagerComponent.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using Base;
  6. namespace Model
  7. {
  8. [ObjectEvent]
  9. public class AppManagerComponentEvent : ObjectEvent<AppManagerComponent>, IAwake
  10. {
  11. public void Awake()
  12. {
  13. this.Get().Awake();
  14. }
  15. }
  16. public class AppManagerComponent: Component
  17. {
  18. private readonly Dictionary<int, Process> processes = new Dictionary<int, Process>();
  19. public void Awake()
  20. {
  21. string[] ips = NetHelper.GetAddressIPs();
  22. StartConfig[] startConfigs = Game.Scene.GetComponent<StartConfigComponent>().GetAll();
  23. foreach (StartConfig startConfig in startConfigs)
  24. {
  25. if (!ips.Contains(startConfig.ServerIP) && startConfig.ServerIP != "*")
  26. {
  27. continue;
  28. }
  29. if (startConfig.AppType.Is(AppType.Manager))
  30. {
  31. continue;
  32. }
  33. StartProcess(startConfig.AppId);
  34. }
  35. this.WatchProcessAsync();
  36. }
  37. private void StartProcess(int appId)
  38. {
  39. OptionComponent optionComponent = Game.Scene.GetComponent<OptionComponent>();
  40. StartConfigComponent startConfigComponent = Game.Scene.GetComponent<StartConfigComponent>();
  41. string configFile = optionComponent.Options.Config;
  42. StartConfig startConfig = startConfigComponent.Get(appId);
  43. #if __MonoCS__
  44. const string exe = @"mono";
  45. string arguments = $"--debug App.exe --appId={startConfig.AppId} --appType={startConfig.AppType} --config={configFile}";
  46. #else
  47. const string exe = @"App.exe";
  48. string arguments = $"--appId={startConfig.AppId} --appType={startConfig.AppType} --config={configFile}";
  49. #endif
  50. Log.Info($"{exe} {arguments}");
  51. try
  52. {
  53. ProcessStartInfo info = new ProcessStartInfo { FileName = exe, Arguments = arguments, CreateNoWindow = true, UseShellExecute = true };
  54. Process process = Process.Start(info);
  55. this.processes.Add(startConfig.AppId, process);
  56. }
  57. catch (Exception e)
  58. {
  59. Log.Error(e.ToString());
  60. }
  61. }
  62. /// <summary>
  63. /// 监控启动的进程,如果进程挂掉了,重新拉起
  64. /// </summary>
  65. private async void WatchProcessAsync()
  66. {
  67. while (true)
  68. {
  69. await Game.Scene.GetComponent<TimerComponent>().WaitAsync(5000);
  70. if (this.Id == 0)
  71. {
  72. return;
  73. }
  74. foreach (int appId in this.processes.Keys.ToArray())
  75. {
  76. Process process = this.processes[appId];
  77. if (!process.HasExited)
  78. {
  79. continue;
  80. }
  81. this.processes.Remove(appId);
  82. process.Dispose();
  83. this.StartProcess(appId);
  84. }
  85. }
  86. }
  87. }
  88. }