using System.IO.Pipes; using MasstransferCommon.Utils; namespace MasstransferCommunicate.Process.Client; internal class PipeClient { private NamedPipeClientStream? _pipeClient; private const string KeyPath = @"Software\Masstransfer\Security"; public event Action MessageReceived; /// /// 启动连接 /// public void Start() { Task.Run(ConnectToServer); } /// /// 等待连接并监听信息 /// private void ConnectToServer() { while (true) { try { Console.WriteLine("正在查找服务端管道id"); var pipeName = RegistryHelper.ReadValue(KeyPath, "PipeId"); if (pipeName == null) { Console.WriteLine("无法找到服务端管道id,等待重试"); Thread.Sleep(1000); continue; } _pipeClient = new NamedPipeClientStream(".", (string)pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); Console.WriteLine("正在连接服务器"); _pipeClient.Connect(5000); Console.WriteLine("已连接到服务器"); using var reader = new StreamReader(_pipeClient); while (_pipeClient.IsConnected) { var message = reader.ReadLine(); if (message != null) { Console.WriteLine($"Received message: {message}"); MessageReceived?.Invoke(message); } } } catch (Exception e) { Console.WriteLine($"Error: {e.Message}"); } finally { _pipeClient?.Dispose(); } Thread.Sleep(1000); // Retry connection after delay } } /// /// 发送消息 /// /// public void SendMessage(string message) { if (_pipeClient is { IsConnected: true }) { var writer = new StreamWriter(_pipeClient) { AutoFlush = true }; writer.WriteLine(message); } } }