c# 利用管道通訊
阿新 • • 發佈:2021-11-03
一、官方的一個列子
/// <summary> /// 服務端---當前例子寫入資料 /// </summary> static void TestServer() { using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.Out)) { // Wait for a client to connect pipeServer.WaitForConnection();try { // Read user input and send that to the client process. using (StreamWriter sw = new StreamWriter(pipeServer)) { for (int i = 0; i < 20; i++) { sw.AutoFlush= true; sw.WriteLine($"Enter text: {i}"); pipeServer.WaitForPipeDrain(); } } } // Catch the IOException that is raised if the pipe is broken // or disconnected.catch (IOException e) { Console.WriteLine("ERROR: {0}", e.Message); } } }
/// <summary> /// 客戶端--當前例子接收資料 /// </summary> static void TestCilent() { Thread thread = new Thread(() => { using (NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", "testpipe", PipeDirection.In)) { // Connect to the pipe or wait until the pipe is available. pipeClient.Connect(); Console.WriteLine("There are currently {0} pipe server instances open.", pipeClient.NumberOfServerInstances); using (StreamReader sr = new StreamReader(pipeClient)) { // Display the read text to the console string temp; while ((temp = sr.ReadLine()) != null) { Console.WriteLine("Received from server: {0}", temp); Thread.Sleep(200); } } } }); //thread.IsBackground = true; //thread.SetApartmentState(ApartmentState.STA); thread.Start(); }
呼叫示例
for (int i = 0; i < 5; i++) { TestCilent(); TestServer(); }