搜索
您的当前位置:首页正文

C#命名管道通信

来源:二三娱乐

C#命名管道通信

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

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

服务器端代码

privatestaticvoidWaitData(){using(NamedPipeServerStream pipeServer =newNamedPipeServerStream("testpipe", PipeDirection.InOut,1))        {try{                pipeServer.WaitForConnection();                pipeServer.ReadMode = PipeTransmissionMode.Byte;using(StreamReader sr =newStreamReader(pipeServer))                {stringcon = sr.ReadToEnd();                    Console.WriteLine(con);                }            }catch(IOException e)            {throwe;            }        }    }

客户端代码

privatestaticvoidSendData(){try{using(NamedPipeClientStream pipeClient =newNamedPipeClientStream("localhost","testpipe", PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.None))            {                pipeClient.Connect();using(StreamWriter sw =newStreamWriter(pipeClient))                {                    sw.WriteLine("hahha");                    sw.Flush();                }            }        }catch(Exception ex)        {throwex;        }          }

Top