zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#命名管道通信详解编程语言

c#通信编程语言 详解 命名 管道
2023-06-13 09:20:25 时间
C#命名管道通信

最近项目中要用c#进程间通信,以前常见的方法包括RMI、发消息等。但在Windows下面发消息需要有窗口,我们的程序是一个后台运行程序,发消息不试用。RMI又用的太多了,准备用管道通信来做消息通信。

管道通信以前在大学学过,包括匿名管道和命名管道。匿名管道只能用在父子进程之间;命名管道可以用在两个进程甚至跨服务器通信。这里给出命名管道的示例。

服务器端代码

 private static void WaitData() 

 using (NamedPipeServerStream pipeServer = 

 new NamedPipeServerStream("testpipe", PipeDirection.InOut, 1)) 

 try 

 pipeServer.WaitForConnection(); 

 pipeServer.ReadMode = PipeTransmissionMode.Byte; 

 using (StreamReader sr = new StreamReader(pipeServer)) 

 string con = sr.ReadToEnd(); 

 Console.WriteLine(con); 

 catch (IOException e) 

 throw e; 

客户端代码

 private static void SendData() 

 try 

 using (NamedPipeClientStream pipeClient = 

 new NamedPipeClientStream("localhost", "testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None)) 

 pipeClient.Connect(); 

 using (StreamWriter sw = new StreamWriter(pipeClient)) 

 sw.WriteLine("hahha"); 

 sw.Flush(); 

 catch (Exception ex) 

 throw ex; 

参考:

如何:使用命名管道进行网络进程间通信

C#中使用命名管道进行进程通信的实例

进程间通信 命名管道实现

8905.html

cjavawindows