1.client:
1 #include "iostream"
2 #include "windows.h"
3
4 using namespace std;
5 void main(int argc,char* argv[])
6 {
7 LPCTSTR Message="the pipe‘s message from a client to server.";
8 if(argc==2)
9 Message=argv[1];
10 DWORD WriteNum;
11
12 if(WaitNamedPipe("\\\\.\\Pipe\\Test",NMPWAIT_WAIT_FOREVER)==FALSE){
13 cout<<"等待链接失败!"<<endl;
14 return;
15 }
16
17 HANDLE hPipe=CreateFile("\\\\.\\Pipe\\Test",GENERIC_READ|18 GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
19 if(hPipe==INVALID_HANDLE_VALUE){
20 cout<<"管道打开失败!"<<endl;
21 return;
22 }
23
24 cout<<"管道连接成功"<<endl;
25 if(WriteFile(hPipe,Message,strlen(Message),&WriteNum,NULL)==FALSE){
26 cout<<"数据写入管道失败!"<<endl;
27 }
28 CloseHandle(hPipe);
29 }
2.server:
1 #include "iostream"
2 #include "windows.h"
3 using namespace std;
4
5 void main(){
6 char buffer[1024];
7 DWORD ReadNum;
8
9 HANDLE m_hPipe=CreateNamedPipe("\\\\.\\Pipe\\Test",PIPE_ACCESS_DUPLEX,PIPE_TYPE_BYTE|PIPE_READMODE_BYTE,1,0,0,1000,NULL);
10
11
12 if(m_hPipe==INVALID_HANDLE_VALUE)
13 cout<<"创建命名管道失败!"<<endl;
14
15 while(1){
16 if(ConnectNamedPipe(m_hPipe,NULL)==FALSE){
17 CloseHandle(m_hPipe);
18 cout<<"与客户机建立链接失败"<<endl;
19 }
20
21 if(ReadFile(m_hPipe,buffer,1024,&ReadNum,NULL)==FALSE)
22 cout<<"read pipe failer!\n"<<endl;
23
24 else{
25 buffer[ReadNum]=0;
26 cout<<"read pipe is:"<<buffer<<".\n"<<endl;
27 }
28
29 if(DisconnectNamedPipe(m_hPipe)==FALSE)
30 cout<<"终止链接失败"<<endl;
31 else
32 cout<<"成功终止链接"<<endl;
33 if(strcmp(buffer,"end")==0)
34 break;
35 }
36
37 CloseHandle(m_hPipe);
38 }
windows namedPipe 命名管道clent and server,布布扣,bubuko.com
时间: 2024-12-07 14:52:13