需要PipeDirection.InOut的NamedPipeServerStream与NamedPipeServer

本文关键字:NamedPipeServer NamedPipeServerStream PipeDirection InOut 需要 | 更新日期: 2023-09-27 18:22:10

我正在寻找一个好的示例,其中NamedPipeServerStream和NamedPipeServer Client可以相互发送消息(当两者的PipeDirection=PipeDirection.InOut时)。目前我只找到了这篇msdn文章。但它只描述了服务器。有人知道客户端连接到此服务器的样子吗?

需要PipeDirection.InOut的NamedPipeServerStream与NamedPipeServer

发生的情况是,服务器坐在那里等待连接,当它有连接时,它会发送一个字符串"waiting"作为简单的握手,然后客户端读取并测试它,然后发送回一个字符串的"Test Message"(在我的应用程序中,它实际上是命令行args)。

请记住,WaitForConnection正在阻塞,因此您可能希望在单独的线程上运行它。

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; }
    }
  }

同类,服务器方法

  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);
  }
}