使用命名管道在 C# 和C++应用程序之间进行持续通信

Continuous Communication between C# and C++ application using Named Pipe

本文关键字:之间 应用程序 通信 C++ 管道      更新时间:2023-10-16

我是IPC的新人。我尝试创建一个客户端服务器应用程序,其中我的服务器是C++应用程序,而客户端是 C#。在此应用程序中,客户端将消息发送到服务器,并根据该消息服务器进行操作。 服务器基本上将图像帧发送到客户端。

使用以下代码,我能够将单帧发送到客户端

我的C++代码

int _count = 0;
const int _scale = 255;
int _bufferSize = ROW * COL;
UINT8 _imageBuffer[391680];
Mat _image;
std::cout << "Server Startingn";
HANDLE hPipe1 = CreateNamedPipe(_T("\\.\pipe\HyperPipe1"),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
PIPE_UNLIMITED_INSTANCES,
4096,
4096,
0,
NULL);
std::cout << "Server Created Succesfullyn";
ConnectNamedPipe(hPipe1, NULL);
std::cout << "Sending Frame to Client";
_image = imread("C:\Users\Chandrapal Singh\Desktop\New folder\Image.bmp", IMREAD_GRAYSCALE);
//_image.clone().convertTo(_image, CV_16U, _scale);
for (int _imageRow = 0; _imageRow < _image.rows; _imageRow++)
{
for (int _imageCol = 0; _imageCol < _image.cols; _imageCol++)
{
_imageBuffer[_count] = _image.at<UINT8>(_imageRow, _imageCol);
_count++;
}
}
DWORD bytesWritten = 0;
WriteFile(hPipe1, _imageBuffer, sizeof(_imageBuffer) * sizeof(UINT8), &bytesWritten, NULL);

我的 C# 代码

int _imageRowSize = 544;
int _imageColSize = 720;
int _count = 0;
byte[] buffer = new byte[_imageColSize * _imageRowSize];
Image<Gray, Byte> image = new Image<Gray, Byte>(_imageColSize,_imageRowSize);
Console.WriteLine("Creating Client Pipe");
NamedPipeClientStream pipe = new NamedPipeClientStream(".", "HyperPipe1", PipeDirection.InOut);
Console.WriteLine("Pipe Created Successfully, Connecting to Server");
pipe.Connect();
Console.WriteLine("Successfully, Connected to Server");
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
_count = 0;      
int read = pipe.Read(buffer, 0, buffer.Length);
for (int _imageRow = 0; _imageRow < 544; _imageRow++)
{
for (int _imageCol = 0; _imageCol < 720; _imageCol++)
{
try
{
image.Data[_imageRow, _imageCol, 0] = buffer[_count];
}catch(Exception exception)
{
Console.WriteLine(exception);
}
_count++;
}
}
CvInvoke.Imshow("Image", image);
Console.WriteLine(_count);
if (read <= 0)
break;
}
}

我想知道如何将消息从 C# 发送到C++,以及我的C++如何持续将图像帧发送到 C#。

在服务器和客户端中创建管道的两个实例或另一个管道,并使用线程同时读取和写入,而不会阻止另一个正在运行的操作