Monday, November 29, 2010

Named Pipes (.NET C#)

Named pipes can be very useful for a variety of functions. I found that a named pipe was the right solution for passing the command line arguments to an already running application (avoiding reloading the application entirely). NamedPipeServerStream and NamedPipeClientStream are the basic classes necessary to create a byte stream pipe between various applications.

A named pipe is a single connection utility. If you make a connection and disconnect you will need to create a new one. You have a few options on how to handle multiple connections with multiple threads. I simply setup a while loop that continued to recreate the named pipe as connections were made and closed. I am sure I still have a lot more to learn about using pipes.


// Server Side
 
NamedPipeServerStream zPipe = new NamedPipeServerStream(PIPE_NAME, PipeDirection.In, 1, PipeTransmissionMode.Message);
zPipe.WaitForConnection();
StringBuilder zBuilder = new StringBuilder();
do
{
    int nLength = zPipe.Read(arrayData, 0, arrayData.Length);
zBuilder.Append(Encoding.UTF8.GetString(arrayData, 0, nLength));
} while (!zPipe.IsMessageComplete);
 
// Client Side
 
NamedPipeClientStream pipeClient = new NamedPipeClientStream(".", PIPE_NAME, PipeDirection.Out);
try
{
pipeClient.Connect(1000);
}
catch (Exception) {return;}
if (pipeClient.IsConnected && pipeClient.CanWrite)
{
    byte[] arrayData = Encoding.UTF8.GetBytes(sMessage);
pipeClient.Write(arrayData, 0, arrayData.Length);
}

Server Pipe
Client Pipe

My previous experience with byte reading and writing to Sockets helped me understand the basics of a pipe. If you have written to streams of any sort you should be able to figure out pipes.

No comments:

Post a Comment