標籤:
原文: C#中使用具名管道進行進程通訊的執行個體
1 建立解決方案NamedPipeExample
在解決方案下面建立兩個項目:Client和Server,兩者的輸出類型均為“Windows 應用程式”。整個程式的結構如所示。
2 實現項目Client
Client僅包含一個名為“用戶端”的表單,如所示。
編寫表單後端代碼,如下所示。
using System;using System.IO;using System.IO.Pipes;using System.Security.Principal;using System.Windows.Forms; namespace Client{ public partial class frmClient : Form { NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost", "testpipe", PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.None); StreamWriter sw = null; public frmClient() { InitializeComponent(); } private void frmClient_Load(object sender, EventArgs e) { try { pipeClient.Connect(5000); sw = new StreamWriter(pipeClient); sw.AutoFlush = true; } catch (Exception ex) { MessageBox.Show("串連建立失敗,請確保服務端程式已經被開啟。"); this.Close(); } } private void btnSend_Click(object sender, EventArgs e) { if (sw != null) { sw.WriteLine(this.txtMessage.Text); } else { MessageBox.Show("未建立串連,不能發送訊息。"); } } }}
3 實現項目Server
Server項目僅包含一個名為“服務端”的表單,如所示。
編寫表單後端代碼,如下所示。
using System;using System.IO;using System.IO.Pipes;using System.Threading;using System.Windows.Forms; namespace Server{ public partial class frmServer : Form { NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut,1,PipeTransmissionMode.Message,PipeOptions.Asynchronous); public frmServer() { InitializeComponent(); } private void frmServer_Load(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(delegate { pipeServer.BeginWaitForConnection((o) => { NamedPipeServerStream pServer = (NamedPipeServerStream)o.AsyncState; pServer.EndWaitForConnection(o); StreamReader sr = new StreamReader(pServer); while (true) { this.Invoke((MethodInvoker)delegate { lsvMessage.Items.Add(sr.ReadLine()); }); } }, pipeServer); }); } }}
4 運行程式
運行Server.exe與Client.exe程式,效果如所示。
執行個體中共發送三次訊息,分別傳遞資料1,2,3。
本例中示範的用戶端和服務端程式均位於本地機器,使用具名管道可以與網路上的其他進程進行通訊。
C#中使用具名管道進行進程通訊的執行個體