命名管道作用:方便程序跨进程通讯;
使用pipeList工具可查询系统中所有命名管道
https://docs.microsoft.com/zh-cn/sysinternals/downloads/pipelist
C#实现代码如下:
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(); } }
欢迎转载,转载请注明:转载自[ http://www.cnblogs.com/zjfree/ ]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具