Sample on NamedPipeServerStream vs NamedPipeServerClient having PipeDirection.InOut needed

Nat picture Nat · Feb 2, 2012 · Viewed 30.8k times · Source

I'm looking for a good sample where NamedPipeServerStream and NamedPipeServerClient can send messages to each other (when PipeDirection = PipeDirection.InOut for both). For now I found only this msdn article. But it describes only server. Does anybody know how client connecting to this server should look like?

Answer

Matt picture Matt · Feb 2, 2012

What happens is the server sits waiting for a connection, when it has one it sends a string "Waiting" as a simple handshake, the client then reads this and tests it then sends back a string of "Test Message" (in my app it's actually the command line args).

Remember that the WaitForConnection is blocking so you probably want to run that on a separate thread.

class NamedPipeExample
{

  private void client() {
    var pipeClient = new NamedPipeClientStream(".", 
      "testpipe", PipeDirection.InOut, PipeOptions.None);

    if (pipeClient.IsConnected != true) { pipeClient.Connect(); }

    StreamReader sr = new StreamReader(pipeClient);
    StreamWriter sw = new StreamWriter(pipeClient);

    string temp;
    temp = sr.ReadLine();

    if (temp == "Waiting") {
      try {
        sw.WriteLine("Test Message");
        sw.Flush();
        pipeClient.Close();
      }
      catch (Exception ex) { throw ex; }
    }
  }

Same Class, Server Method

  private void server() {
    var pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, 4);

    StreamReader sr = new StreamReader(pipeServer);
    StreamWriter sw = new StreamWriter(pipeServer);

    do {
      try {
        pipeServer.WaitForConnection();
        string test;
        sw.WriteLine("Waiting");
        sw.Flush();
        pipeServer.WaitForPipeDrain();
        test = sr.ReadLine();
        Console.WriteLine(test);
      }

      catch (Exception ex) { throw ex; }

      finally {
        pipeServer.WaitForPipeDrain();
        if (pipeServer.IsConnected) { pipeServer.Disconnect(); }
      }
    } while (true);
  }
}