一、流程
1. 服務端用CreateNamedPipe創建一個命名管道並使用ConnectNamedPipe等待客戶端的連接。
2. 客戶端使用WaitNamedPipe連接成功後,用CreateFile打開管道並使用WriteFile向管道中寫入一段數據(即向服務端發送消息)。
3. 服務端使用ReadFile從管道中讀取數據後(即收到消息)再向管道中寫入確認信息表明已經收到客戶端傳輸的數據(即通知客戶端已收到)。
4. 客戶端收到確認信息後結束,調用CloseHandle關閉管道(該管道是CreateFile打開的)。
5.服務端使用DisconnectNamedPipe和CloseHandle關閉管道。
二、實例
先運行服務器,再運行客戶端
服務端
// ServicePip.cpp : 此文件包含 "main" 函數。程序執行將在此處開始並結束。
//
#include <iostream>
#include <windows.h>
#include <ctime>
using namespace std;
#define pStrPipeName L"\\\\.\\pipe\\NamePipe_MoreWindows"
int main()
{
printf(" 命名管道 服務器\n");
printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
printf("創建命名管道並等待連接\n");
HANDLE hPipe = CreateNamedPipe(pStrPipeName, PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES, 0, 0, NMPWAIT_WAIT_FOREVER, 0);
if (ConnectNamedPipe(hPipe, NULL) != NULL)//等待連接。
{
printf("連接成功,開始接收數據\n");
const int BUFFER_MAX_LEN = 256;
char szBuffer[BUFFER_MAX_LEN];
memset(szBuffer, 0, BUFFER_MAX_LEN);
DWORD dwLen;
//接收客戶端發送的數據
ReadFile(hPipe, szBuffer, BUFFER_MAX_LEN, &dwLen, NULL);//讀取管道中的內容(管道是一種特殊的文件)
printf("接收到數據長度爲%d字節\n", dwLen);
printf("具體數據內容如下:%s\n", szBuffer);
//確認已收到數據,併發送消息給客戶端
printf("向客戶端發送已經收到標誌\n");
strcpy_s(szBuffer, "服務器已經收到");//服務器發送的消息
WriteFile(hPipe, szBuffer, strlen(szBuffer) + 1, &dwLen, NULL);
}
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);//關閉管道
return 0;
}
客戶端
#include <iostream>
#include <windows.h>
#include <ctime>
#include <conio.h>
using namespace std;
#define BUFSIZE 5
#define pStrPipeName L"\\\\.\\pipe\\NamePipe_MoreWindows"
int main()
{
printf(" 命名管道 客戶端\n");
printf(" -- by MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n");
printf("按任意鍵以開始連接命名管道\n");
_getch();
printf("開始等待命名管道\n");
if (WaitNamedPipe(pStrPipeName, NMPWAIT_WAIT_FOREVER) == FALSE)
{
printf("Error! 連接命名管道失敗\n");
return 0;
}
printf("打開命名管道\n");
HANDLE hPipe = CreateFile(pStrPipeName, GENERIC_READ | GENERIC_WRITE, 0,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
printf("向服務端發送數據\n");
const int BUFFER_MAX_LEN = 256;
char szBuffer[BUFFER_MAX_LEN];
memset(szBuffer, 0, BUFFER_MAX_LEN);
DWORD dwLen = 0;
//向服務端發送數據
sprintf_s(szBuffer, "進程%d說\"%s\"", GetCurrentProcessId(), "Hello World!");
WriteFile(hPipe, szBuffer, strlen(szBuffer) + 1, &dwLen, NULL);
printf("數據寫入完畢共%d字節\n", dwLen);
//接收服務端發回的數據
ReadFile(hPipe, szBuffer, BUFFER_MAX_LEN, &dwLen, NULL);//讀取管道中的內容(管道是一種特殊的文件)
printf("接收服務端發來的確認信息長度爲%d字節\n", dwLen);
printf("具體數據內容如下:%s\n", szBuffer);
CloseHandle(hPipe);
system("pause");
return 0;
}
參考: