C#WPF匿名管道AnonymousPipeClientStream管道方向输出不起作用

时间:2016-09-02 05:51:17

标签: c# wpf ipc

我正在开发一个测试应用程序,使用Anonymous Pipes在两个进程之间进行通信。我可以从ServerView向ClientView发送一条消息,但由于管道连接抛出异常,我不能反过来。

ServerCode

 public class PipeServerHandler
{
    private static AnonymousPipeServerStream serverSenderStream;
    private static AnonymousPipeServerStream serverReceiverStream;
    private static StreamWriter sw;
    private static StreamReader sr;


    public void ServerStart()
    {
        serverSenderStream = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
        serverReceiverStream = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable);

        string senderID = serverSenderStream.GetClientHandleAsString();
        string receiverID = serverReceiverStream.GetClientHandleAsString();

        ProcessStartInfo process = new ProcessStartInfo(@"C:\Users\VinushaP\Documents\Visual Studio 2015\Projects\CommunicationProject\ClientView\bin\Debug\ClientView.exe", senderID + "_" + receiverID);
        process.UseShellExecute = false;

        Process clientProcess = Process.Start(process);

        serverSenderStream.DisposeLocalCopyOfClientHandle();

        sr = new StreamReader(serverReceiverStream);
    }

    public string ReadData()
    {
        string temp;
        temp = sr.ReadLine();

        return temp;
    }
}

客户代码

public class PipeClientHandler
{

    private static AnonymousPipeClientStream clientReceiverStream;
    private static AnonymousPipeClientStream clientSenderStream;
    private static StreamReader sr;
    private static StreamWriter sw;

    public void ClientStart(string[] args)
    {
        string[] id = args[0].Split('_');
        string senderID = id[0];
        string receiverID = id[1];

        clientReceiverStream = new AnonymousPipeClientStream(PipeDirection.In, senderID);
        clientSenderStream = new AnonymousPipeClientStream(PipeDirection.Out, receiverID);

        sw = new StreamWriter(clientSenderStream);
        sw.AutoFlush = true;
    }

    public void WriteStream(string data)
    {
        sw.WriteLine(data);
        clientSenderStream.WaitForPipeDrain();
    }

}

这是app.xaml.cs类,它捕获命令行参数

private void Application_Startup(object sender, StartupEventArgs e)
    {
        PipeClientHandler handler = new PipeClientHandler();

        if (e.Args.Length > 0)
        {
            handler.ClientStart(e.Args);
        }
    }

当从PipeServerHandler向PipeClienHandler发送数据时,它运行良好,但是当我从PipeClientHandler向PipeServerHandler发送数据时,它不会向我显示任何消息。

clientSenderStream错误

enter image description here

1 个答案:

答案 0 :(得分:0)

我知道这有点旧,但匿名管道是一种方式。您需要两个匿名管道来进行双向通信。