C#和C++之间的双工名称管道

Duplex NamePipe between C# and C++

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

我在C#服务器和C++之间进行双工通信时遇到了一些问题:

目标是创建管道,从客户端读取内容并写回内容。如果我只是从客户那里阅读或写信给客户,一切都很好,但我不能一个接一个地同时做这两件事!

这是我的C#服务器:

// Create a name pipe
 using (NamedPipeServerStream pipeStream = new NamedPipeServerStream("TestPipe"))
 {
   Console.WriteLine("[Server] Pipe created {0}", pipeStream.GetHashCode());
   // Wait for a connection
   pipeStream.WaitForConnection();
   Console.WriteLine("[Server] Pipe connection established");
   //Reading Part
   using (StreamReader sr = new StreamReader(pipeStream))
   {
      string temp;
      while ((temp = sr.ReadLine()) != null)
      {
         Console.WriteLine("{0}: {1}", DateTime.Now, temp);
       }
     }
     //Writing Part
     using (StreamWriter sw = new StreamWriter(pipeStream))
     {
        sw.AutoFlush = true;
        String st = "send Back";
        sw.WriteLine(st);
     }
 }

这是C++客户端:

HANDLE hFile;
BOOL flg;
DWORD dwWrite;
char szPipeUpdate[200];
hFile = CreateFile(L"\\.\pipe\TestPipe", GENERIC_WRITE|GENERIC_READ,
                           0, NULL, OPEN_EXISTING,
                           0, NULL);

 strcpy(szPipeUpdate,"Sending some data from client to server!");
 if(hFile == INVALID_HANDLE_VALUE)
  { 
        DWORD dw = GetLastError();
        printf("CreateFile failed for Named Pipe clientn:" );
  }
  else
  {
      flg = WriteFile(hFile, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL);
      if (FALSE == flg)
      {
         printf("WriteFile failed for Named Pipe clientn");
      }
      else
      {
         printf("WriteFile succeeded for Named Pipe clientn");
      }
  }
  printf("Let's read!n");
  //Read the datas sent by the server
  BOOL fFinishRead = FALSE;
  do
    {
        char chResponse[200];
        DWORD cbResponse, cbRead;
        cbResponse = sizeof(chResponse);
        fFinishRead = ReadFile(
            hFile,                  // Handle of the pipe
            chResponse,             // Buffer to receive the reply
            cbResponse,             // Size of buffer in bytes
            &cbRead,                // Number of bytes read 
            NULL                    // Not overlapped 
            );
        if (!fFinishRead && ERROR_MORE_DATA != GetLastError())
        {
            DWORD  dwError = GetLastError();
            wprintf(L"ReadFile from pipe failed w/err 0x%08lxn", dwError);
            break;
        }
        std::cout << chResponse;
    } while (!fFinishRead); // Repeat loop if ERROR_MORE_DATA
 CloseHandle(hFile);

使用服务器;Client NamedPipeStreams您需要确保连接的至少一端始终在尝试读取,否则写入将失败。我想这是你的客户和;服务器在听/写。这里有一个快速的博客文章解释了这种行为。

我建议在客户端上使用两个流&服务器,两者都从同一管道读取/写入。