繁体   English   中英

在命名管道上读写

[英]Reading and writing on and from named pipe

我正在为此目的编写的测试应用程序中尝试使用命名管道的 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();之后运行var line = reader.ReadLine(); 并且似乎永远不会到达下一行。 所以这就是为什么我认为它无法从管道中读取任何值。 但是我需要改变什么? 我想用write输出值。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM