C#使用匿名管道在本地程式之間進行通訊

小弟季義欽發表於2013-08-07

from CSDN

匿名管道提供的功能比命名管道少,但它需要的系統開銷也少。您可以使用匿名管道更加輕鬆地在本地計算機上進行程式間通訊。不能使用匿名管道通過網路進行通訊。


下面的示例演示使用匿名管道將字串從父程式傳送到子程式的方式。此示例使用OutPipeDirection值在父程式中建立一個AnonymousPipeServerStream物件。然後,父程式通過使用客戶端控制程式碼建立一個AnonymousPipeClientStream物件來建立一個子程式。該子程式的In值為PipeDirection

然後,父程式將使用者提供的字串傳送給子程式。該字串將顯示在子程式中的控制檯上。

下面的示例演示伺服器程式。

using System;
using System.IO;
using System.IO.Pipes;
using System.Diagnostics;

class PipeServer
{
    static void Main()
    {
        Process pipeClient = new Process();

        pipeClient.StartInfo.FileName = "pipeClient.exe";

        using (AnonymousPipeServerStream pipeServer =
            new AnonymousPipeServerStream(PipeDirection.Out,
            HandleInheritability.Inheritable))
        {
            // Show that anonymous pipes do not support Message mode.
            try
            {
                Console.WriteLine("[SERVER] Setting ReadMode to \"Message\".");
                pipeServer.ReadMode = PipeTransmissionMode.Message;
            }
            catch (NotSupportedException e)
            {
                Console.WriteLine("[SERVER] Exception:\n    {0}", e.Message);
            }

            Console.WriteLine("[SERVER] Current TransmissionMode: {0}.",
                pipeServer.TransmissionMode);

            // Pass the client process a handle to the server.
            pipeClient.StartInfo.Arguments =
                pipeServer.GetClientHandleAsString();
            pipeClient.StartInfo.UseShellExecute = false;
            pipeClient.Start();

            pipeServer.DisposeLocalCopyOfClientHandle();

            try
            {
                // Read user input and send that to the client process.
                using (StreamWriter sw = new StreamWriter(pipeServer))
                {
                    sw.AutoFlush = true;
                    // Send a 'sync message' and wait for client to receive it.
                    sw.WriteLine("SYNC");
                    pipeServer.WaitForPipeDrain();
                    // Send the console input to the client process.
                    Console.Write("[SERVER] Enter text: ");
                    sw.WriteLine(Console.ReadLine());
                }
            }
            // Catch the IOException that is raised if the pipe is broken
            // or disconnected.
            catch (IOException e)
            {
                Console.WriteLine("[SERVER] Error: {0}", e.Message);
            }
        }

        pipeClient.WaitForExit();
        pipeClient.Close();
        Console.WriteLine("[SERVER] Client quit. Server terminating.");
    }
}

下面的示例演示客戶端程式。伺服器程式啟動客戶端程式,併為該程式提供一個客戶端控制程式碼。應該將從客戶端程式碼得到的可執行檔案命名為pipeClient.exe並在執行該伺服器程式之前將其複製到伺服器可執行檔案所在的目錄中。

using System;
using System.IO;
using System.IO.Pipes;

class PipeClient
{
    static void Main(string[] args)
    {
        if (args.Length > 0)
        {
            using (PipeStream pipeClient =
                new AnonymousPipeClientStream(PipeDirection.In, args[0]))
            {
                // Show that anonymous Pipes do not support Message mode.
                try
                {
                    Console.WriteLine("[CLIENT] Setting ReadMode to \"Message\".");
                    pipeClient.ReadMode = PipeTransmissionMode.Message;
                }
                catch (NotSupportedException e)
                {
                    Console.WriteLine("[CLIENT] Execption:\n    {0}", e.Message);
                }

                Console.WriteLine("[CLIENT] Current TransmissionMode: {0}.",
                   pipeClient.TransmissionMode);

                using (StreamReader sr = new StreamReader(pipeClient))
                {
                    // Display the read text to the console
                    string temp;

                    // Wait for 'sync message' from the server.
                    do
                    {
                        Console.WriteLine("[CLIENT] Wait for sync...");
                        temp = sr.ReadLine();
                    }
                    while (!temp.StartsWith("SYNC"));

                    // Read the server data and echo to the console.
                    while ((temp = sr.ReadLine()) != null)
                    {
                        Console.WriteLine("[CLIENT] Echo: " + temp);
                    }
                }
            }
        }
        Console.Write("[CLIENT] Press Enter to continue...");
        Console.ReadLine();
    }
}



相關文章