C#和C++之间的双工名称管道
Duplex NamePipe between C# and C++
我在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您需要确保连接的至少一端始终在尝试读取,否则写入将失败。我想这是你的客户和;服务器在听/写。这里有一个快速的博客文章解释了这种行为。
我建议在客户端上使用两个流&服务器,两者都从同一管道读取/写入。
相关文章:
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- IPC使用多个管道和分支进程来运行Python程序
- 如何创建函数管道,以便函数一个接一个地运行?
- Gstreamer 管道从命令 lne 到 c 代码
- 外壳包装器句柄/执行交互式命令管道C++ UNIX
- 将旧管道转换为现代 openGL 时出现问题
- 如何使用管道在父级和子级之间来回传递文件
- 在没有管理员权限的情况下连接到同一网络中的命名管道
- 如何测量管道延迟?
- 我如何使用此程序管道多个命令?C++
- 先进先出:一个进程永远不会从管道读取
- Node.js fs.open() 在尝试打开 4 个以上的命名管道 (FIFO) 后挂起
- 使用模板而不是虚拟方法的管道模式
- 我可以写入关闭的套接字并强制纠正损坏的管道错误吗?
- 在 Azure DevOps 构建管道中使用英特尔C++编译器为 Linux 环境构建C++代码
- Opencv GStreamer管道在Raspberry Pi 4上不起作用
- 阻塞管道连接命名管道不触发
- GLib-ERROR:为GWakeup创建管道:打开的文件太多
- 向 vulkan 管道添加额外的 UBO 会停止所有几何体渲染
- 在命名管道中发送标准::字符串流