C#使用命名管道Pipe進行程序通訊例項詳解
阿新 • • 發佈:2020-12-30
1.新建解決方案NamedPipeExample 新建兩個專案:Client和Server,兩者的輸出型別均為“Windows 應用程式”。整個程式的結構如下圖所示。
此Form1為Client的窗體,如下圖所示。
後端程式碼,如下。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.IO.Pipes; using System.Security.Principal; namespace Client { public partial class Form1 : Form { NamedPipeClientStream pipeClient = new NamedPipeClientStream("localhost","testpipe",PipeDirection.InOut,PipeOptions.Asynchronous,TokenImpersonationLevel.None); StreamWriter sw = null; public Form1() { InitializeComponent(); } private void Form1_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("未建立連線,不能傳送訊息。"); } } } }
此Form1為Server的窗體,如下圖所示
後端程式碼,如下。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.IO.Pipes; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Server { public partial class Form1 : Form { NamedPipeServerStream pipeServer = new NamedPipeServerStream("testpipe",1,PipeTransmissionMode.Message,PipeOptions.Asynchronous); public Form1() { InitializeComponent(); } private void textBox1_TextChanged(object sender,EventArgs e) { } private void Form1_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.Text = sr.ReadLine(); }); } },pipeServer); }); } private void maskedTextBox1_MaskInputRejected(object sender,MaskInputRejectedEventArgs e) { } } }
先執行Server再執行Client
到此這篇關於C#使用命名管道Pipe進行程序通訊例項詳解的文章就介紹到這了,更多相關C# Pipe程序通訊內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!