【问题标题】:Reading and writing on and from named pipe在命名管道上读写
【发布时间】:2019-10-22 23:16:14
【问题描述】:

我正在为此目的编写的测试应用程序中尝试使用命名管道的 IPC。我想从管道中读取一个值,但读取器似乎没有读取任何内容。

我正在启动一个服务器进程和一个客户端。服务器使用名为InitPipe 的命名管道来告诉客户端用于通信的新管道的名称。之后,一个新的服务器进程和客户端连接到新管道,另一个服务器进程和客户端断开连接,InitPipe 重新打开,新进程与服务器通信。 客户端将数据写入管道,新的服务器进程应该读取数据。这就是问题所在。服务器似乎没有从管道中获取值。

private void svr_task(string comPipe)
    {
        var server = new NamedPipeServerStream(comPipe);
        write("Com-Pipe: " + comPipe);        //'write' just writes to a TextBox on the UI thread

        server.WaitForConnection();
        write("Client connected: " + comPipe);

        StreamReader reader = new StreamReader(server);
        StreamWriter writer = new StreamWriter(server);

        while (server.IsConnected)
        {
            var line = reader.ReadLine();     //the program doesn't seem to run past this line

            write(line);
        }
        write("Client disconnected: " + comPipe);
        server.Dispose();
        write("Com-Pipe closed: " + comPipe);
    }

    private void cl_start()
    {
        //This is for InitPipe
        var clientInit = new NamedPipeClientStream("InitPipe");
        NamedPipeClientStream client = new NamedPipeClientStream("InitPipe");

        clientInit.Connect();
        Dispatcher.Invoke(() => stat_cl1.Content = "Initialize...");
        StreamReader reader = new StreamReader(clientInit);
        StreamWriter writer = new StreamWriter(clientInit);

        while (clientInit.IsConnected)
        {
            var line = reader.ReadLine();
            client = new NamedPipeClientStream(line);
            clientInit.Dispose();
        }

        //This is where the communication with the server thread starts
        client.Connect();
        Dispatcher.Invoke(() => stat_cl1.Content = "Connected");
        reader = new StreamReader(client);
        writer = new StreamWriter(client);

        while (client.IsConnected)
        {
            string line = Dispatcher.Invoke(() => box_cl1.Text);      //read a value from a textbox (This works)

            writer.Write(line);
            writer.Flush();
        }

        client.Dispose();
        Dispatcher.Invoke(() => stat_cl1.Content = "Not connected");
    }

我希望服务器线程从客户端线程接收值。 UI 线程未锁定,因此我可以启动另一个客户端,该客户端也可以连接到服务器线程。 在 VS 中调试并单步执行代码时,它只在 var line = reader.ReadLine(); 之后运行,并且似乎永远不会进入下一行。所以这就是为什么我认为它无法从管道中读取任何值。但是我需要改变什么?我想用write 输出值。

【问题讨论】:

    标签: c# wpf multithreading ipc named-pipes


    【解决方案1】:

    我遇到了类似的问题。它与命名管道的工作方式有关。您可以一次写入或读取命名管道。尝试不要同时将 StreamReader 和 StreamWriter 附加到流。我通过单独的阅读器流和编写器流解决了这个问题。此外,您可以为多个客户端使用相同的管道名称,您只需在客户端连接后创建一个新的服务器实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多