发送方:
1、创建管道
2、阻塞式连接(等待接收方)
3、发送数据
#include<iostream>
#include<windows.h>
#include<ctime>
using namespace std;
int main()
{
HANDLE hPipe = CreateNamedPipe(TEXT("\\\\.\\Pipe\\mypipe"),PIPE_ACCESS_DUPLEX,PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_WAIT
,PIPE_UNLIMITED_INSTANCES,0,0,NMPWAIT_WAIT_FOREVER,0);//创建了一个命名管道
if(ConnectNamedPipe(hPipe, NULL)==TRUE)//
{
cout<<"Connected!"<<endl;
}
char buf[256]="Hello Pipe";
DWORD wlen=0;
while(1)
{
WriteFile(hPipe,buf,sizeof(buf),&wlen,0);
cout<<"Send:"<<buf<<endl;
_sleep(1000);
}
return 1;
}
接收方:
1、非阻塞式尝试连接
2、创建管道文件
3、接受文件
#include<iostream>
#include<windows.h>
#include<ctime>
using namespace std;
int main()
{
while(WaitNamedPipe(TEXT("\\\\.\\Pipe\\mypipe"), NMPWAIT_WAIT_FOREVER)==FALSE)
{
}
HANDLE hPipe=CreateFile(TEXT("\\\\.\\Pipe\\mypipe"), GENERIC_READ | GENERIC_WRITE, 0,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
char buf[256];
DWORD rlen=0;
while(1)
{
if(ReadFile(hPipe,buf,256,&rlen,NULL)==FALSE)//读取管道中的内容(管道是一种特殊的文件)
{
CloseHandle(hPipe);//关闭管道
break;
}
else
{
cout<<"Rcv:"<<buf<<endl;
}
}
return 0;
}