using System.IO.Pipes; namespace MasstransferCommunicate.Process.Client; internal class PipeClient(string pipeName) { private NamedPipeClientStream? _pipeClient; public event Action MessageReceived; /// /// 启动连接 /// public void Start() { Task.Run(ConnectToServer); } /// /// 等待连接并监听信息 /// private void ConnectToServer() { while (true) { try { _pipeClient = new NamedPipeClientStream(".", 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); } } }