1.client:ios
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:windows
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 }