windows namedPipe 具名管道clent and server

來源:互聯網
上載者:User

標籤:c   style   class   blog   code   java   

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             else32                 cout<<"成功終止連結"<<endl;33             if(strcmp(buffer,"end")==0)34                 break;35         }36 37     CloseHandle(m_hPipe);38 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.