windows namedPipe 命名管道clent and server

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 }

 

转载于:https://www.cnblogs.com/593213556wuyubao/p/3774083.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值