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

Async pipe between C# and C++

本文关键字:异步 管道 之间 c++      更新时间:2023-10-16

我试图在c#(服务器)和c++(客户端)之间发送数据。现在我只能在它们之间成功发送一个数据。我如何从c#异步(实时)发送多个值到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);

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

另外,请注意,由于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());
  }
}