using System; using System.Diagnostics; using System.IO.Pipes; using System.Text; using System.Text.Json; using System.Threading; using Notify.Serialization; namespace Notify.Ipc; /// /// 瘦客户端侧:把一条 PipeMessage 发给 Host,Host 不在则拉起后重试 /// public static class PipeClient { public static bool Send(PipeMessage message) { var json = JsonSerializer.Serialize(message, AppJsonContext.Default.PipeMessage); var bytes = Encoding.UTF8.GetBytes(json); if (TrySend(bytes, 300)) { return true; } // Host 未运行:拉起后等待其管道就绪再重试,最多约 5 秒 StartHost(); for (var i = 0; i < 50; i++) { Thread.Sleep(100); if (TrySend(bytes, 300)) { return true; } } return false; } private static bool TrySend(byte[] bytes, int timeoutMs) { try { using var client = new NamedPipeClientStream(".", IpcConstants.PipeName, PipeDirection.Out); client.Connect(timeoutMs); client.Write(bytes, 0, bytes.Length); client.Flush(); return true; } catch { return false; } } private static void StartHost() { try { var exe = Environment.ProcessPath; if (exe is null) { return; } Process.Start(new ProcessStartInfo { FileName = exe, Arguments = "host", UseShellExecute = false, CreateNoWindow = true, }); } catch { // 拉起失败则发送会重试超时后放弃 } } }