using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using Netch.Models; using Netch.Utils; namespace Netch.Controllers { public abstract class Controller { /// /// 控制器名 /// public string Name; /// /// 进程实例 /// public Process Instance; /// /// 主程序名(不含扩展名) /// public string MainFile; private List _startedKeywords = new List(); private List _stoppedKeywords = new List(); protected bool RedirectStd = true; protected void StartedKeywords(params string[] texts) { foreach (var text in texts) { _startedKeywords.Add(text); } } protected void StoppedKeywords(params string[] texts) { foreach (var text in texts) { _stoppedKeywords.Add(text); } } /// /// 当前状态 /// protected State State = State.Waiting; public abstract void Stop(); /// /// 停止 /// protected void StopInstance() { try { if (Instance == null || Instance.HasExited) return; Instance.Kill(); Instance.WaitForExit(); } catch (Exception e) { Logging.Error($"停止 {MainFile} 错误:\n" + e); } } public void ClearLog() { try { if (File.Exists($"logging\\{Name}.log")) File.Delete($"logging\\{Name}.log"); } catch (Exception) { // ignored } } /// /// 写日志 /// /// /// 是否为空 protected bool Write(string s) { if (string.IsNullOrWhiteSpace(s)) return false; try { File.AppendAllText($"logging\\{Name}.log", s + Global.EOF); } catch (Exception e) { Logging.Error($"写入{Name}日志错误:\n" + e); } return true; } public Process GetProcess() { var p = new Process { StartInfo = { FileName = Path.GetFullPath($"bin\\{MainFile}"), WorkingDirectory = $"{Global.NetchDir}\\bin", CreateNoWindow = true, RedirectStandardError = RedirectStd, RedirectStandardInput = RedirectStd, RedirectStandardOutput = RedirectStd, UseShellExecute = false }, EnableRaisingEvents = true }; return p; } /// /// 接收输出数据 /// /// 发送者 /// 数据 protected void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { // 写入日志 if (!Write(e.Data)) return; // 检查启动 if (State == State.Starting) { if (Instance.HasExited) { State = State.Stopped; return; } foreach (var s in _startedKeywords) { if (e.Data.Contains(s)) { State = State.Started; return; } } foreach (var s in _stoppedKeywords) { if (e.Data.Contains(s)) { State = State.Stopped; return; } } } } } }