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#コード:

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();

        }
    }
}
4

2 に答える 2

11

StreamWriterまたはを破棄StreamReaderすると、基になるストリームが閉じます。

したがって、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);
            }
    }

pipeStream.Close()ストリームをusingステートメントでラップするため、コメント化された関数は必要ないことにも注意してください。

于 2012-05-24T15:26:18.993 に答える
7

わかりました、私のアプリケーションで動作しました.... 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パラメーターでした。これにより、サーバーはクライアント接続を待機します。

于 2012-05-25T15:13:23.727 に答える