C++有名管道通信简单示例

  • 有名管道,简单的理解可以理解成,一个通过命名不同来实现通信的一种方式。
  • 简单的有名管道实现逻辑如下:
* 1. CreateNamedPipe 创建一个有名管道,在系统中
* 2。::ConnectNamedPipe 监听客户端的连接,获取数据

作为客户端而言

1.::WaitNamedPipe(PIPE_CLIENT_NAME, NMPWAIT_WAIT_FOREVER)// 连接到有名管道
2.::CreateFile 打开有名管道
3.WriteFile:往有名管道内记录数据
  • 实例代码
    ** 服务端部分
// PipeConnection.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
using namespace std;

#define PIPE_SERVER_NAME L"\\\\.\\pipe\\Pipe_Server"
#define BUF_SIZE 1024

//创建管道服务端
bool CreatePipeServer()
{
	//创建命名管道
	char buf_msg[BUF_SIZE];
	DWORD num_rcv; //实际接收到的字节数
	HANDLE h_pipe = ::CreateNamedPipe(PIPE_SERVER_NAME,PIPE_ACCESS_INBOUND,PIPE_READMODE_BYTE|PIPE_WAIT,PIPE_UNLIMITED_INSTANCES,BUF_SIZE,BUF_SIZE,0,nullptr);
	if (h_pipe == INVALID_HANDLE_VALUE)
	{
		cout << "无效管道" << endl;
		return false;
	}
	//等待客户端连接
	if (::ConnectNamedPipe(h_pipe,nullptr))
	{
		memset(buf_msg,0,BUF_SIZE);
		if (::ReadFile(h_pipe,buf_msg,BUF_SIZE,&num_rcv,nullptr))
		{

			cout << buf_msg << endl;
		}
	}
	::CloseHandle(h_pipe);
}


int _tmain(int argc, _TCHAR* argv[])
{
	CreatePipeServer();
	system("pause");
	return 0;
}


  • 客户端部分
// PipeClientConnection.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#define PIPE_CLIENT_NAME L"\\\\.\\pipe\\Pipe_Server"

#define BUF_SIZE 1024
using namespace std;

//创建客户端连接
bool CreateClientPipe()
{
	HANDLE h_pipe;
	char buf_msg[] = "Test for named pipe...";
	DWORD num_rcv; //实际接收到的字节数
	cout << "Try to connect named pipe...\n";
	//连接命名管道
	if (::WaitNamedPipe(PIPE_CLIENT_NAME, NMPWAIT_WAIT_FOREVER))
	{
		//打开指定命名管道
		h_pipe = ::CreateFile(PIPE_CLIENT_NAME, GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
		if (h_pipe == INVALID_HANDLE_VALUE)
		{
			cerr << "Failed to open the appointed named pipe!Error code: " << ::GetLastError() << "\n";
			::system("pause");
			return 0;
		}
		else
		{
			if (::WriteFile(h_pipe, buf_msg, BUF_SIZE, &num_rcv, nullptr))
			{
				cout << "Message sent successfully...\n";
			}
			else
			{
				cerr << "Failed to send message!Error code: " << ::GetLastError() << "\n";
				::CloseHandle(h_pipe);
				::system("pause");
				return 1;
			}
		}
		::CloseHandle(h_pipe);
	}
	return false;
}


int _tmain(int argc, _TCHAR* argv[])
{
	CreateClientPipe();
	return 0;
}


发布了365 篇原创文章 · 获赞 80 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/Giser_D/article/details/103819951