环境: windows10 + vs2015
参考:
https://zhuanlan.zhihu.com/p/386564892
下面是命名管道的服务器以及客户端代码:
服务端
#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
const char *pStrPipeName = "\\\\.\\pipe\\MyNamePipe";
// 创建管道
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 (hPipe != INVALID_HANDLE_VALUE) {
printf("Successfully created pipe!\n");
printf("Waiting for client to connect...\n");
}
// 等待客户端连接
if (ConnectNamedPipe(hPipe, NULL) != NULL) {
printf("The connection is successful!\n");
printf("Start to receive data:\n");
CHAR Buffer[1024] = { 0 };
DWORD dwNumberOfBytesRead = 0;
// 接收客户端发送的数据
ReadFile(hPipe, Buffer, sizeof(Buffer), &dwNumberOfBytesRead, NULL);
printf("data len: %d\n", dwNumberOfBytesRead);
printf("content:%s\n", Buffer);
// 确认已收到数据
printf("Send a received flag to the client!\n");
strcpy_s(Buffer, "done");
WriteFile(hPipe, Buffer, strlen(Buffer) + 1, &dwNumberOfBytesRead, NULL);
}
// 断开连接并关闭管道
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
cin.get();
return 0;
}
客户端
#include <windows.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
const char *pStrPipeName = "\\\\.\\pipe\\MyNamePipe";
printf("Connecting to pipe...\n");
if (WaitNamedPipe(pStrPipeName, NMPWAIT_WAIT_FOREVER) == FALSE) {
printf("Failed to connect to pipe!\n");
return 0;
}
printf("Open pipe!\n");
HANDLE hPipe = CreateFile(pStrPipeName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
printf("Send data to the server!\n");
CHAR Buffer[1024] = { 0 };
DWORD dwNumberOfBytesWritten = 0;
// 向服务端发送数据
sprintf_s(Buffer, "Process %d said: %s", GetCurrentProcessId(), "Hello World!");
WriteFile(hPipe, Buffer, strlen(Buffer) + 1, &dwNumberOfBytesWritten, NULL);
printf("Send data len :%d \n", dwNumberOfBytesWritten);
// 接收服务端发回的数据
ReadFile(hPipe, Buffer, sizeof(Buffer), &dwNumberOfBytesWritten, NULL);
printf("Reply data len: %d\n", dwNumberOfBytesWritten);
printf("content:%s\n", Buffer);
CloseHandle(hPipe);
cin.get();
return 0;
}
说明: 先启动服务端,再启动客户端.
完