Cómo: Usar canalizaciones anónimas para la comunicación entre procesos locales

Actualización: noviembre 2007

Las canalizaciones anónimas proporcionan menos funcionalidad que canalizaciones con nombre, pero también requieren menos esfuerzo. Puede utilizar las canalizaciones anónimas para facilitar la comunicación entre procesos en un equipo local. No se puede utilizar las canalizaciones anónimas para la comunicación a través de una red.

Ejemplo

En el ejemplo siguiente se muestra una manera de enviar una cadena de un proceso primario a un proceso secundario mediante canalizaciones anónimas. En este ejemplo se crea un objeto AnonymousPipeServerStream en un proceso primario con un valor PipeDirection de Out. A continuación, el proceso primario crea un proceso secundario mediante un identificador de cliente para crear un objeto AnonymousPipeClientStream. El proceso secundario tiene un valor PipeDirection de In.

El proceso primario envía a continuación una cadena proporcionada por usuario al proceso secundario. La cadena se muestra a la consola en el proceso secundario.

En el ejemplo siguiente se muestra el proceso del servidor.

Imports System
Imports System.IO
Imports System.IO.Pipes
Imports System.Diagnostics

Class PipeServer
    Shared Sub Main()
        Dim pipeClient As New Process()
        pipeClient.StartInfo.FileName = "pipeClient.exe"

        Using pipeServer As New AnonymousPipeServerStream( _
                PipeDirection.Out, HandleInheritability.Inheritable)

            Console.WriteLine("Current TransmissionMode: {0}.", _
                              pipeServer.TransmissionMode)

            'Anonymous pipes do not support Message mode.
            Try
                Console.WriteLine("Setting ReadMode to 'Message'.")
                pipeServer.ReadMode = PipeTransmissionMode.Message
            Catch e As Exception
                Console.WriteLine("EXCEPTION: {0}", e.Message)
            End Try

            ' 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 sw As New StreamWriter(pipeServer)
                    sw.AutoFlush = True
                    Console.Write("Enter text: ")
                    sw.WriteLine(Console.ReadLine())
                End Using
            Catch e As Exception
                Console.WriteLine("ERROR: {0}", e.Message)
            End Try

            pipeClient.WaitForExit()
            pipeClient.Close()
        End Using
    End Sub
End Class
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))
        {
            Console.WriteLine("Current TransmissionMode: {0}.",
                pipeServer.TransmissionMode);

            // Anonymous pipes do not support Message mode.
            try
            {
                Console.WriteLine("Setting ReadMode to \"Message\".");
                pipeServer.ReadMode = PipeTransmissionMode.Message;
            }
            catch (NotSupportedException e)
            {
                Console.WriteLine("EXCEPTION: {0}", e.Message);
            }

            // 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;
                    Console.Write("Enter text: ");
                    sw.WriteLine(Console.ReadLine());
                }
            }
            // Catch the IOException that is raised if the pipe is broken
            // or disconnected.
            catch (IOException e)
            {
                Console.WriteLine("ERROR: {0}", e.Message);
            }
        }

        pipeClient.WaitForExit();
        pipeClient.Close();
    }
}

En el ejemplo siguiente se muestra el proceso del cliente. El proceso de servidor inicia el proceso de cliente y da un identificador de cliente a ese proceso. El ejecutable resultante del código de cliente debe denominarse pipeClient.exe y copiarse en el mismo directorio que el ejecutable del servidor antes de ejecutar el proceso de servidor.

Imports System
Imports System.IO
Imports System.IO.Pipes

Class PipeClient

    Shared Sub Main(ByVal args As String())
        If (args.Length > 0) Then

            Using pipeClient As New AnonymousPipeClientStream( _
                PipeDirection.In, args(0))

                Console.WriteLine("Current TransmissionMode: {0}.", _
                   pipeClient.TransmissionMode)

                ' Anonymous Pipes do not support Message mode.
                Try
                    Console.WriteLine("Setting ReadMode to 'Message'.")
                    pipeClient.ReadMode = PipeTransmissionMode.Message
                Catch e As NotSupportedException
                    Console.WriteLine("EXCEPTION: {0}", e.Message)
                End Try

                Using sr As New StreamReader(pipeClient)

                    ' Display the read text to the console
                    Dim temp As String
                    temp = sr.ReadLine()
                    While Not temp = Nothing
                        Console.WriteLine(temp)
                        temp = sr.ReadLine()
                    End While
                End Using
            End Using
        End If
        Console.Write("Press Enter to continue...")
        Console.ReadLine()
    End Sub
End Class
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]))
            {

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

                // Anonymous Pipes do not support Message mode.
                try
                {
                    Console.WriteLine("Setting ReadMode to \"Message\".");
                    pipeClient.ReadMode = PipeTransmissionMode.Message;
                }
                catch (NotSupportedException e)
                {
                    Console.WriteLine("EXCEPTION: {0}", e.Message);
                }

                using (StreamReader sr = new StreamReader(pipeClient))
                {
                    // Display the read text to the console
                    string temp;
                    while ((temp = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(temp);
                    }
                }
            }
        }
        Console.Write("Press Enter to continue...");
        Console.ReadLine();
    }
}

Vea también

Tareas

Cómo: Usar canalizaciones con nombre para la comunicación entre procesos a través de una red

Conceptos

Canalizaciones