NamedPipeServerStream和NamedPipeServerClient上的示例需要PipeDirection.InOut

Nat*_*Nat 21 c# named-pipes

我正在寻找一个很好的示例,其中NamedPipeServerStream和NamedPipeServerClient可以相互发送消息(当PipeDirection = PipeDirection.InOut时).现在我只发现了这篇msdn文章.但它只描述了服务器.有人知道连接到这台服务器的客户端应该如何吗?

Mat*_*att 35

发生的事情是服务器等待连接,当它有一个发送字符串"Waiting"作为一个简单的握手时,客户端然后读取它并测试它然后发回一串"测试消息"(在我的应用程序中它是实际上是命令行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; }
    }
  }
Run Code Online (Sandbox Code Playgroud)

同一类,服务器方法

  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);
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!你帮助我意识到我的代码有什么问题.我正在离开服务器等待从客户端(在单独的线程中)读取内容,同时尝试向客户端发送消息.代码挂在sw.WriteLine上.似乎服务器不可能等待消息并同时发送消息. (2认同)