使用命名管道实现C++和C#之间的双向通信

9
我正在尝试在VC++ 6应用程序和C#应用程序之间实现双向通信。我使用了命名管道。在我的C++代码中,我可以从C#客户端读取消息,但是服务器会“死掉”,然后我必须重新启动它。
我想做的是让C#应用程序连接到C++应用程序,请求状态,然后C++应用程序检查状态,然后返回“忙”或“空闲”。
我无法向C#客户端写回任何内容,因为它说连接已关闭。我已经尝试过的一些事情已被我注释掉了。
以下是C++代码(作为线程启动):
UINT CNamedPipe::StartNamedPipeServer()
{
LPTSTR lpszPipename = "\\\\.\\pipe\\SAPipe"; 
    HANDLE hPipe; 
    BOOL flg;
    DWORD dwWrite,dwRead;
    char szServerUpdate[200];
    char szClientUpdate[200];

    hPipe = CreateNamedPipe (    lpszPipename, 
                                PIPE_ACCESS_DUPLEX,
                                PIPE_TYPE_MESSAGE | 
                                PIPE_READMODE_MESSAGE | 
                                PIPE_NOWAIT,                    //changed from nowait
                                PIPE_UNLIMITED_INSTANCES,    // max. instances 
                                BUFSIZE,                    // output buffer size 
                                BUFSIZE,                    // input buffer size 
                                PIPE_TIMEOUT,                // client time-out 
                                NULL);                        // no security attribute 

    if (hPipe == INVALID_HANDLE_VALUE) 
        return 0;

    ConnectNamedPipe(hPipe, NULL);

    while(m_bServerActive)  //This seems to work well ....
    {

        //Read from client
        flg = ReadFile(hPipe,szClientUpdate,strlen(szClientUpdate),&dwRead, NULL);

        if(flg) //Read something from the client!!!!
        {
            CString csMsg,csTmp;

            for(int i=0;i<dwRead;i++){
                csTmp.Format("%c",szClientUpdate[i]);
                csMsg += csTmp;
            }


            AfxMessageBox("Client message: " + csMsg);

            strcpy( szServerUpdate,"busy");

            //Write status to Client
            flg = WriteFile(hPipe, szServerUpdate, strlen(szServerUpdate), &dwWrite, NULL);

            EndServer();
            StartServer();
        }

    }

    return 0;

}

C# Code:

public void ThreadStartClient(object obj)
    {
        // Ensure that we only start the client after the server has created the pipe
        ManualResetEvent SyncClientServer = (ManualResetEvent)obj;

        // Only continue after the server was created -- otherwise we just fail badly
        // SyncClientServer.WaitOne();

        using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", "SAPipe"))
        {
            // The connect function will indefinately wait for the pipe to become available
            // If that is not acceptable specify a maximum waiting time (in ms)
            pipeStream.Connect();

            //Write from client to server
           using (StreamWriter sw = new StreamWriter(pipeStream))
            {
                sw.WriteLine("What's your status?");
           }

            //Read server reply
            /*using (StreamReader sr = new StreamReader(pipeStream))
            {
                string temp = "";
                temp = sr.ReadLine();   //Pipe is already closed here ... why?

                MessageBox.Show(temp);

            }*/

            //pipeStream.Close();

        }
    }
}
2个回答

11

释放 StreamWriterStreamReader 将会关闭底层流。

因此,你的 using 语句将导致流关闭。

    public void ThreadStartClient(object obj)
    {
            // Ensure that we only start the client after the server has created the pipe
            ManualResetEvent SyncClientServer = (ManualResetEvent)obj;

            // Only continue after the server was created -- otherwise we just fail badly
            // SyncClientServer.WaitOne();

            using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", "SAPipe"))
            {
                // The connect function will indefinately wait for the pipe to become available
                // If that is not acceptable specify a maximum waiting time (in ms)
                pipeStream.Connect();


                //Write from client to server
                StreamWriter sw = new StreamWriter(pipeStream))
                sw.WriteLine("What's your status?");

                //Read server reply
                StreamReader sr = new StreamReader(pipeStream)
                string temp = "";
                temp = sr.ReadLine();   //Pipe is already closed here ... why?

                MessageBox.Show(temp);
            }
    }

需要注意的是,因为你将流包装在 using 语句中,所以注释掉的 pipeStream.Close() 函数是不必要的。


谢谢,这非常有帮助。我会修改我的代码并查看发生了什么。正如你可能猜到的那样,我是新手C#。 - Bob Moore
没问题,记得在投票下面按一下检查,这样你的批准率会更高! - Blam

8
Ok,我已经为我的应用程序解决了问题....谢谢Blam! 以下是C ++服务器代码(在线程中运行):
UINT CNamedPipe::StartNamedPipeServer()
{
    if(!m_bServerActive)
        return 0;

    LPTSTR lpszPipename = "\\\\.\\pipe\\MyPipe"; 
        HANDLE hPipe; 
        BOOL flg;
        DWORD dwWrite,dwRead;
        char szServerUpdate[200];
        char szClientUpdate[200];

        hPipe = CreateNamedPipe (    lpszPipename, 
                                    PIPE_ACCESS_DUPLEX,
                                    PIPE_TYPE_MESSAGE | 
                                    PIPE_READMODE_MESSAGE | 
                                    PIPE_WAIT,                  //HAS TO BE THIS
                                    PIPE_UNLIMITED_INSTANCES,    // max. instances 
                                    BUFSIZE,                    // output buffer size 
                                    BUFSIZE,                    // input buffer size 
                                    PIPE_TIMEOUT,                // client time-out 
                                    NULL);                        // no security attribute 

        if (hPipe == INVALID_HANDLE_VALUE) 
            return 0;

        ConnectNamedPipe(hPipe, NULL);


        strcpy( szServerUpdate,"busy");

        //Write status to Client
        flg = WriteFile(hPipe, szServerUpdate, strlen(szServerUpdate), &dwWrite, NULL);

        EndServer();
        StartServer();

        return 0;
}

这是C#客户端:

public void ThreadStartClient(object obj)
        {
            // Ensure that we only start the client after the server has created the pipe
            ManualResetEvent SyncClientServer = (ManualResetEvent)obj;

            using (NamedPipeClientStream pipeStream = new NamedPipeClientStream(".", "MyPipe", PipeDirection.InOut))
            {

                // The connect function will indefinately wait for the pipe to become available
                // If that is not acceptable specify a maximum waiting time (in ms)
                pipeStream.Connect();

                if (!pipeStream.IsConnected)    //It thinks it's connected but can't read anything ....
                {
                    MessageBox.Show("Failed to connect ....");
                    return;
                }

                //Read server reply
                StreamReader sr = new StreamReader(pipeStream);

                char[] c = new char[200];

                while (sr.Peek() >= 0)
                {
                    sr.Read(c, 0, c.Length);
                }

                string s = new string(c);
                MessageBox.Show(s);
            }
        }

我实际上并没有从客户端向服务器发送任何东西,因为我不需要...其中关键的是CreateNamedPipe()函数中的PIPE_WAIT参数。这使得服务器等待客户端连接。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接