AppManagerComponent.cs 2.3 KB

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