Named pipes usage. Multiple clients, one server, multiple parallel requests

Adrian Zanescu picture Adrian Zanescu · Apr 7, 2011 · Viewed 12.9k times · Source

I'm trying to implement a named pipes server in .NET. The client will be C++. The nature of the data sent is not relevant to the question.

My first naive implementation looks something like:

using (NamedPipeServerStream stream = 
                new NamedPipeServerStream(PipeName,
                                          PipeDirection.InOut, 
                                          numberOfListeners,
                                          PipeTransmissionMode.Message))
{
     while (true)
     {
          try
          {
              stream.WaitForConnection();

              var request = ReadRequest(stream);

              var reply = Process(request);
              WriteReply(stream, reply);
              stream.WaitForPipeDrain();
          }
          catch (Exception ex)
          {
              //TO DO: log
          }
     }
 }

Am I approaching this right?

What would happen when two clients open a connection at the same time ?

Will they share the same stream and data will be intermingled ?

How can I avoid this?

Any ideas or resources on this will help. I'm pretty new to this topic.

Answer

Chris Dickson picture Chris Dickson · Apr 7, 2011

You will want the server to be able to handle concurrent client connections, and each client to connect to the server on a different instance of the pipe, rather than trying to do everything on one pipe instance as your code does at present. When the client is finished, you want to release the instance of the pipe used when talking to that client, not reuse it.

This answer gives a pseudo-code outline of one way to do this.

Also note that in Message mode you need to read from the pipe in a loop, until the IsMessageComplete property becomes true. It's the only way to guarantee you get each complete message. Also be aware that "message" in message mode means a stream of bytes written by the sender in one Write call to the pipe.

Client streams can't get mixed up with each other: a pipe instance has just two ends, THE client and THE server.