AppManagerComponent.cs 2.2 KB

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