本文介绍了NamedPipeServerStream与NamedPipeServerClient上的示例需要PipeDirection.InOut的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个好样本,其中NamedPipeServerStream和NamedPipeServerClient可以彼此发送消息(当PipeDirection = PipeDirection.InOut时).到目前为止,我仅找到此msdn文章.但它仅描述服务器.有人知道客户端连接到该服务器的样子吗?

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?

推荐答案

发生的事情是服务器坐在等待连接的位置,当服务器建立连接时,它以简单的握手方式发送字符串"Waiting",然后客户端读取并进行测试,然后发送回"Test Message"字符串(在我的应用中,它实际上是命令行参数).

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).

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

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

相同的类,服务器方法

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

这篇关于NamedPipeServerStream与NamedPipeServerClient上的示例需要PipeDirection.InOut的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 17:59