好文:https://blog.csdn.net/skyroben/article/details/71513385
例子:
Sever.cpp
#include <iostream>
#include "windows.h"
//命名管道
#define PIPE_NAME "\\\\.\\Pipe\\test"
void Server()
{
char outBuffer[1024] = { 0 }; //服务端发送的数据
char inBuffer[1024] = { 0 }; //服务端接收的数据
DWORD WriteNum = 0;
DWORD ReadNum = 0;
while (true) {
// 1.创建命名管道
printf("创建命名管道!\n");
HANDLE hPipe = CreateNamedPipeA(PIPE_NAME, PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, 0, 0, 1000, NULL);
if (hPipe == INVALID_HANDLE_VALUE) { printf("【error】创建命名管道失败!\n"); system("pause"); CloseHandle(hPipe); return; }
// 2.等待客户端的连接(阻塞)
printf("等待客户端连接...\n");
if (ConnectNamedPipe(hPipe, NULL) == FALSE) { printf("连接失败!ErrorCode = %d \n", GetLastError()); CloseHandle(hPipe); system("pause"); return; }
printf("成功建立连接...\n");
// 3.收发消息
while (true)
{
Sleep (1000);
//向客户端发送消息
strcpy(outBuffer, "Hello NamePipe !");
if (WriteFile(hPipe, outBuffer, strlen(outBuffer), &WriteNum, NULL) == FALSE) { printf("发送数据失败!连接已断开... ErrorCode = %d \n", GetLastError()); break; }
printf("【服务端】发送消息:%s \n", outBuffer);
//从客户端接收消息(阻塞)
if (ReadFile(hPipe, inBuffer, 1024, &ReadNum, NULL) == FALSE) { printf("读取数据失败!连接已断开... ErrorCode = %d \n", GetLastError()); break; }
printf("【服务端】接收到消息:%s \n", inBuffer);
}
// 4.关闭管道
printf("关闭管道!\n\n");
CloseHandle(hPipe);
}
system("pause");
}
int main()
{
Server();
system("pause");
}
Client.cpp
#include <iostream>
#include "windows.h"
//定义命名管道
#define PIPE_NAME "\\\\.\\Pipe\\test"
void Client()
{
char outBuffer[1024] = { 0 }; //客户端发送的数据
char inBuffer[1024] = { 0 }; //客户端接收的数据
DWORD WriteNum=0;
DWORD ReadNum=0;
// 1.连接服务端,打开命名管道
if (WaitNamedPipeA(PIPE_NAME, NMPWAIT_WAIT_FOREVER) == FALSE) { printf("等待命名管道实例失败!\n"); return; }
HANDLE hPipe = CreateFileA(PIPE_NAME, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hPipe == INVALID_HANDLE_VALUE) { printf("打开命名管道失败!\n"); CloseHandle(hPipe); return; }
printf("成功连接到服务器!\n");
// 2.收发消息
while (true)
{
Sleep (1);
//从服务端接收消息
if (ReadFile(hPipe, inBuffer, 1024, &ReadNum, NULL) == FALSE) { printf("接收数据失败!\n"); break; }
printf("【客户端】接收到消息:%s \n", inBuffer);
//向服务端发送消息
strcpy(outBuffer, "Yes !");
if (WriteFile(hPipe, outBuffer, strlen(outBuffer), &WriteNum, NULL) == FALSE) { printf("发送数据失败!\n"); break; }
printf("【客户端】发送消息:%s \n", outBuffer);
}
// 4.关闭管道
printf("关闭管道!\n\n");
CloseHandle(hPipe);
system("pause");
}
int main()
{
Client();
system("pause");
}