C#具名管道通訊

來源:互聯網
上載者:User

標籤:

原文: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#具名管道通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.