在不关闭管道的情况下不断收听管道

时间:2014-08-12 12:34:04

标签: c# named-pipes

我有一个32位winform应用程序将jpeg图像发送到64位winform应用程序。 我使用管道(IPC)。

不是关闭服务器管道并重新打开它,而是希望保持打开并处理图像。

我想知道以下代码是否正确?另外,我如何知道何时收到完整的字节数据包?我必须在我的客户端调用代码中的字节数组中放置一个“标题”,其中前4个字节保持整个字节数组/数据包的大小,就像我使用套接字一样吗?使用管道有更简单的方法吗?

这是我的服务器管道代码:

    static NamedPipeServerStream pipeServer = null;
    public static void WaitForConnectionCallBack(IAsyncResult iar)
    {
        pipeServer = (NamedPipeServerStream)iar.AsyncState;
        pipeServer.EndWaitForConnection(iar);
        while (pipeServer != null)
        {
            if (pipeServer.IsConnected == true)
            {
                byte[] imageData = new byte[100000];
                pipeServer.Read(imageData, 0, imageData.Length);
                //do stuff with data
            }
        }
    }
    static string _pipeName = "";
    public static void Listen(string PipeName)
    {
        // Set to class level var so we can re-use in the async callback method
        _pipeName = PipeName;
        // Create the new async pipe 
        NamedPipeServerStream pipeServer = new NamedPipeServerStream(PipeName,
           PipeDirection.In, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
        // Wait for a connection
        pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
    }

1 个答案:

答案 0 :(得分:2)

嗨我认为添加带有数组长度/大小的标题是好的 并且可能添加校验和或其他东西