使用Win32控制台实现命名管道通信

接收端:

//server
//命名管道采用基于连接的可靠传输方式,只能一对一传输
#include <windows.h>
#include <iostream>

#define BUF_SIZE 1024

using std::cerr;
using std::cout;
using std::endl;

int main()
{
	HANDLE h_pipe;
	char buf_msg[BUF_SIZE];
	DWORD num_rcv; //实际接收到的字节数
	//创建命名管道,命名为MyPipe,消息只能从客户端流向服务器,读写数据采用阻塞模式,字节流形式,超时值置为0表示采用默认的50毫秒
	h_pipe = ::CreateNamedPipe(L"\\\\.\\pipe\\MyPipe", PIPE_ACCESS_INBOUND, PIPE_READMODE_BYTE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, BUF_SIZE, BUF_SIZE, 0, nullptr);
	if (h_pipe == INVALID_HANDLE_VALUE)
	{
		cerr << "Failed to create named pipe!Error code: " << ::GetLastError() << "\n";
		system("pause");
		return 1;
	}
	else
	{
		cout << "Named pipe created successfully...\n";
	}
	//等待命名管道客户端连接
	if (::ConnectNamedPipe(h_pipe, nullptr))
	{
		cout << "A client connected...\n";
		memset(buf_msg, 0, BUF_SIZE);
		//读取数据
		if (::ReadFile(h_pipe, buf_msg, BUF_SIZE, &num_rcv, nullptr))
		{
			cout << "Message received: " << buf_msg << "\n";
		}
		else
		{
			cerr << "Failed to receive message!Error code: " << ::GetLastError() << "\n";
			::CloseHandle(h_pipe);
			::system("pause");
			return 1;
		}
	}
	::CloseHandle(h_pipe);
	::system("pause");
	return 0;
}

发送端:

//client
#include <windows.h>
#include <iostream>

#define BUF_SIZE 1024

using std::cerr;
using std::cout;
using std::endl;

int main()
{
	HANDLE h_pipe;
	char buf_msg[] = "Test for named pipe...";
	DWORD num_rcv; //实际接收到的字节数
	cout << "Try to connect named pipe...\n";
	//连接命名管道
	if (::WaitNamedPipe(L"\\\\.\\pipe\\MyPipe", NMPWAIT_WAIT_FOREVER))
	{
		//打开指定命名管道
		h_pipe = ::CreateFile(L"\\\\.\\pipe\\MyPipe", 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 1;
		}
		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);
	}
	::system("pause");
	return 0;
}

参考链接

https://www.cnblogs.com/jzincnblogs/p/5192763.html

posted @ 2020-07-05 19:12  任小七  阅读(474)  评论(0编辑  收藏  举报