C#和C ++之间的异步管道

时间:2014-06-23 11:25:34

标签: c# c++ asynchronous pipe

我试图在C#(服务器)和C ++(客户端)之间发送数据。现在我只能在它们之间成功发送一个数据。如何从C#async(实时)向C ++发送多个值?

C#服务器

using (NamedPipeServerStream PServer1 =
            new NamedPipeServerStream("MyNamedPipe", PipeDirection.InOut))
        {
            Console.WriteLine("Server created");
            Console.WriteLine("Waiting for client connection...");
            PServer1.WaitForConnection();

            Console.WriteLine("Client conencted");

            try
            {
                // Read user input and send that to the client process. 
                using (StreamWriter sw = new StreamWriter(PServer1))
                {
                    sw.AutoFlush = true;
                    Console.Write("Enter text: ");
                    sw.WriteLine(Console.ReadLine());
                }

            }
            // Catch the IOException that is raised if the pipe is broken 
            // or disconnected. 
            catch (IOException e)
            {
                Console.WriteLine("ERROR: {0}", e.Message);
            }
            //PServer1.Close();
        }

C ++客户端

HANDLE hPipe;

//Connect to the server pipe using CreateFile()
hPipe = CreateFile( 
    g_szPipeName,   // pipe name 
    GENERIC_READ |  // read and write access 
    GENERIC_WRITE, 
    0,              // no sharing 
    NULL,           // default security attributes
    OPEN_EXISTING,  // opens existing pipe 
    0,              // default attributes 
    NULL);          // no template file 

if (INVALID_HANDLE_VALUE == hPipe) 
{
    printf("\nError occurred while connecting" 
        " to the server: %d", GetLastError()); 
    return 1;  //Error
}
else
{
    printf("\nCreateFile() was successful.");
}

//Read server response
char szBuffer[BUFFER_SIZE];
DWORD cbBytes;
BOOL bResult = ReadFile( 
    hPipe,                // handle to pipe 
    szBuffer,             // buffer to receive data 
    sizeof(szBuffer),     // size of buffer 
    &cbBytes,             // number of bytes read 
    NULL);                // not overlapped I/O 

if ( (!bResult) || (0 == cbBytes)) 
{
    printf("\nError occurred while reading" 
        " from the server: %d", GetLastError()); 
    CloseHandle(hPipe);
    return 1;  //Error
}
else
{
    printf("\nReadFile() was successful.");
}

printf("\nServer sent the following message: %s", szBuffer);

//CloseHandle(hPipe);

1 个答案:

答案 0 :(得分:0)

如果要发送多条消息,则必须在客户端和服务器中设置循环。

另外,请注意,由于using语句,正在调用Pipe的Dispose()方法,因此关闭它。因此,您必须在using块中包含循环。

类似于:

(服务器侧)

using(var sw = new StreamWriter(PServer1))
{
  sw.AutoFlush = true;

  while(Condition) // This could be done by analyzing the user's input and looking for something special...
  {
    Console.Write("Enter text: ");
    sw.WriteLine(Console.ReadLine());
  }
}