0

我在 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\0";
        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 client\n:" );
  }
  else
  {
      flg = WriteFile(hFile, szPipeUpdate, strlen(szPipeUpdate), &dwWrite, NULL);
      if (FALSE == flg)
      {
         printf("WriteFile failed for Named Pipe client\n");
      }
      else
      {
         printf("WriteFile succeeded for Named Pipe client\n");
      }
  }

  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%08lx\n", dwError);
            break;
        }
        std::cout << chResponse;

    } while (!fFinishRead); // Repeat loop if ERROR_MORE_DATA
 CloseHandle(hFile);
4

1 回答 1

1

使用 Server & Client NamedPipeStreams,您需要确保连接的至少一端始终尝试读取,否则写入将失败。我猜这是您的客户端和服务器之间的时间问题,无论是在听/写。这是一篇快速博客文章,也解释了这种行为。

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

于 2012-08-28T17:12:30.177 回答