码迷,mamicode.com
首页 > Windows程序 > 详细

C#命名管道通信

时间:2015-11-21 00:31:00      阅读:467      评论:0      收藏:0      [点我收藏+]

标签:

原文:C#命名管道通信

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#中使用命名管道进行进程通信的实例

进程间通信 - 命名管道实现

C#命名管道通信

标签:

原文地址:http://www.cnblogs.com/lonelyxmas/p/4982637.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!