Sample on NamedPipeServerStream vs NamedPipeServerClient having PipeDirection.InOut needed

前端 未结 1 1323
心在旅途
心在旅途 2021-01-31 10:34

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

相关标签:
1条回答
  • 2021-01-31 11:07

    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);
      }
    }
    
    0 讨论(0)
提交回复
热议问题