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

進程間通信 - 命名管道實現


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM