windows 通信之命名管道

client
//等待实例化
//创建管道
//发收数据
//关闭会话

#include "pch.h"
#include 
#include 
#include 
#include
using namespace std;
void  main()
{
	char buffer[1024];
	DWORD WriteNum;

	if (WaitNamedPipe(L"\\\\.\\Pipe\\test", NMPWAIT_WAIT_FOREVER) == FALSE)
	{
		cout << "等待命名管道实例失败!" << endl;
		return;
	}

	HANDLE hPipe = CreateFile(L"\\\\.\\Pipe\\test", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hPipe == INVALID_HANDLE_VALUE)
	{
		cout << "创建命名管道失败!" << endl;
		CloseHandle(hPipe);
		return;
	}
	cout << "与服务器连接成功!" << endl;
	printf("connect ok!\n");

	while (1)
	{
		gets_s(buffer);//等待数据输入

		if (WriteFile(hPipe, buffer, strlen(buffer), &WriteNum, NULL) == FALSE)
		{
			cout << "数据写入管道失败!" << endl;
			break;
		}
	}

	cout << "关闭管道!" << endl;
	CloseHandle(hPipe);
	system("pause");
}

server

#include 
#include 

using namespace std;

//1建立连接
//2等待连接
//3收发数据
//4关闭会话

void main()
{
	char buffer[1024];
	DWORD ReadNum;

	HANDLE hPipe = CreateNamedPipe("\\\\.\\Pipe\\test", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 0, 0, 1000, NULL);
	if (hPipe == INVALID_HANDLE_VALUE)
	{
		cout << "创建命名管道失败!%s" << GetLastError() << endl;
		CloseHandle(hPipe);
		return;
	}

	if (ConnectNamedPipe(hPipe, NULL) == FALSE)
	{
		cout << "连接失败!%s" << GetLastError() << endl;
		CloseHandle(hPipe);
		return; 
	}
	cout << "连接成功!" << endl;
	printf("server init ok!");
	while (1)
	{
		if (ReadFile(hPipe, buffer, 1024, &ReadNum, NULL) == FALSE)
		{
			cout << "读取数据失败!" << GetLastError() << endl;
			CloseHandle(hPipe);
			return;
		}

		buffer[ReadNum] = '\0';
		cout << "读取数据:" << buffer << endl;
	}

	cout << "关闭管道!" << endl;
	CloseHandle(hPipe);
	system("pause");
}

你可能感兴趣的:(Windows)