命名管道做用:方便程序跨進程通信;工具
使用pipeList工具可查詢系統中全部命名管道this
https://docs.microsoft.com/zh-cn/sysinternals/downloads/pipelistspa
C#實現代碼以下:code
public partial class Form1 : Form { // 命名管道客戶端 NamedPipeClientStream pipeClient = null; StreamWriter swClient = null; StreamReader srClient = null; public Form1() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; } // 建立命名管道 private void button1_Click(object sender, EventArgs e) { backgroundWorker1.RunWorkerAsync(); txtInfo.AppendText("建立命名管道" + Environment.NewLine); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { using (NamedPipeServerStream pipeServer = new NamedPipeServerStream("testPipe", PipeDirection.InOut)) { pipeServer.WaitForConnection(); var data = new byte[10240]; var count = pipeServer.Read(data, 0, 10240); StreamReader sr = new StreamReader(pipeServer); using (StreamWriter sw = new StreamWriter(pipeServer)) { sw.AutoFlush = true; sw.WriteLine("hello " + DateTime.Now.ToString()); while (true) { string str = sr.ReadLine(); File.AppendAllText(Application.StartupPath + "//log.txt", DateTime.Now.ToLocalTime().ToString() + " " + str + Environment.NewLine); txtInfo.AppendText(str + Environment.NewLine); sw.WriteLine("send to client " + DateTime.Now.ToString()); Thread.Sleep(1000); } } } } // 鏈接命名管道 private void button2_Click(object sender, EventArgs e) { try { pipeClient = new NamedPipeClientStream("localhost", "testPipe", PipeDirection.InOut, PipeOptions.Asynchronous, TokenImpersonationLevel.None); pipeClient.Connect(5000); swClient = new StreamWriter(pipeClient); srClient = new StreamReader(pipeClient); swClient.AutoFlush = true; backgroundWorker2.RunWorkerAsync(); txtInfo.AppendText("鏈接命名管道" + Environment.NewLine); } catch (Exception ex) { MessageBox.Show("鏈接創建失敗,請確保服務端程序已經被打開。" + ex.ToString()); } } // 發送消息 private void button3_Click(object sender, EventArgs e) { if (swClient != null) { swClient.WriteLine(this.textBox1.Text); } else { MessageBox.Show("未創建鏈接,不能發送消息。"); } } // 接收消息 private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { while (true) { if (srClient != null) { txtInfo.AppendText(srClient.ReadLine() + System.Environment.NewLine); } } } private void Form1_Load(object sender, EventArgs e) { // button1.PerformClick(); } }