【问题标题】:Sample on NamedPipeServerStream vs NamedPipeServerClient having PipeDirection.InOut needed需要 PipeDirection.InOut 的 NamedPipeServerStream 与 NamedPipeServerClient 的示例
【发布时间】:2012-02-25 05:01:18
【问题描述】:

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

【问题讨论】:

    标签: c# named-pipes


    【解决方案1】:

    发生的情况是服务器等待连接,当它有一个连接时,它会发送一个字符串“Waiting”作为简单的握手,然后客户端读取它并对其进行测试,然后发送回一个“测试消息”字符串(在我的应用程序实际上是命令行参数)。

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

    【讨论】:

    • 谢谢!你帮助我意识到我的代码有什么问题。我让服务器等待从客户端读取某些内容(在单独的线程中),同时试图向客户端发送消息。代码挂在 sw.WriteLine 上。服务器似乎不可能同时等待消息并发送一个。
    • 我的问题是记得刷新流写入器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多