我在 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);