server:
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <Windows.h>
#include <process.h>
#include <stdlib.h>
#include <iostream>
const char *pStrPipeNameGet = "\\\\.\\pipe\\recv_data_pipe";// 注意命名管道的规则:\\servername\pipe\pipename,如果是本地管道则servername可以使用点“.”
HANDLE hSemaphore;
void RecvDataThread(PVOID p)
{
printf("管道服务器已经启动,等待连接...\n");
// 创建一个命名管道
HANDLE hPipe = CreateNamedPipe(pStrPipeNameGet, // 管道的名称
PIPE_ACCESS_DUPLEX,// 管道的打开模式
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,// 管道的使用模式
PIPE_UNLIMITED_INSTANCES, // 管道可以接收的最大客户量
0, // 输出缓冲区长度;零表示用默认设置
0, // 输入缓冲区长度;零表示用默认设置
NMPWAIT_WAIT_FOREVER, // 管道的默认等待超时
NULL);// 安全属性结构
const int BUFFER_MAX_LEN = 1024;
DWORD dwRecvDataLen;
char buf[BUFFER_MAX_LEN];
// 等待客户端管道的连接
if (ConnectNamedPipe(hPipe, NULL) != NULL)
{
printf("连接成功,开始接收数据\n");
while (true)
{
// 接收客户端发送的数据
if (!ReadFile(hPipe, buf, BUFFER_MAX_LEN, &dwRecvDataLen, NULL))
break;
printf("接收到来自客户端的数据长度为%d字节\n", dwRecvDataLen);
printf("具体数据内容如下:");
std::cout << buf << std::endl;
}
}
else
{
printf("连接失败\n");
}
// 断开所有与命名管道上的连接
DisconnectNamedPipe(hPipe);
// 关闭命名管道
CloseHandle(hPipe);
ReleaseSemaphore(hSemaphore, 1, NULL);
}
int _tmain(int argc, _TCHAR* argv[])
{
hSemaphore = CreateSemaphore(NULL, 0, 1, TEXT("my_semaphore"));
_beginthread(RecvDataThread, NULL, NULL);
WaitForSingleObject(hSemaphore, INFINITE);
std::cout << "按任意键退出." << std::endl;
std::cin.get();
return 0;
}
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <conio.h>
#include <iostream>
const char *pStrPipeName = "\\\\.\\pipe\\recv_data_pipe";
const int BUFFER_MAX_LEN = 1024;
char buf[BUFFER_MAX_LEN];
int _tmain(int argc, _TCHAR* argv[])
{
printf("等待管道服务器......\r\n");
if (!WaitNamedPipe(pStrPipeName, 100000))
{
printf("连接管道服务器失败.\r\n");
std::cin.get();
return 0;
}
HANDLE hPipe = CreateFile(pStrPipeName, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
while (true)
{
printf("请输入要向服务端发送的数据,回车键结束,最大1024个字节\r\n");
DWORD dwLen = 0;
int bufSize;
std::cin >> buf;
bufSize = strlen(buf)+1;
buf[bufSize] = '\0';
//向服务端发送数据
if (WriteFile(hPipe, buf, bufSize, &dwLen, NULL)) {
printf("数据写入完毕共%d字节\r\n", dwLen);
}
else
{
printf("数据写入失败\n");
}
if (strcmp(buf, "exit") == 0)
break;
}
CloseHandle(hPipe);
return 0;
}