命名管道服务器流与命名管道客户端的示例,需要使用PipeDirection.InOut

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

37

服务器会一直等待连接,当它接收到一个连接请求后,会发送一个简单的握手字符串“Waiting”,客户端会读取并测试该字符串,然后发送一个字符串“Test Message”(在我的应用程序中实际上是命令行参数)。

请记住,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);
  }
}

2
谢谢!你帮我意识到了代码的问题所在。我一直让服务器等待从客户端读取数据(在独立线程中),同时也试图向客户端发送消息。代码卡在了 sw.WriteLine 上。看来服务器不可能同时等待消息和发送消息。 - Nat
我的问题是记得刷新流写入器。 - Jason Allen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接