AppManagerComponent.cs 2.4 KB

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