服务端void CPipetest1Dlg::OnOK() { // TODO: Add extra validation here HANDLE hSvrHndle=CreateNamedPipe("\\\\.\\pipe\\pipetest\\", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | // message-read mode PIPE_WAIT, // blocking mode PIPE_UNLIMITED_INSTANCES, BUFSIZE, BUFSIZE, NMPWAIT_WAIT_FOREVER, NULL); if( INVALID_HANDLE_VALUE == hSvrHndle) { AfxMessageBox("Error create/open pipe"); return; } while(1) { if(ConnectNamedPipe(hSvrHndle,NULL)){ printf("connecting pipe succeed\n"); break; } } DWORD bytesread=-1; char rBuf[512],shareBuf[512]; BOOL flag=TRUE; while(flag){ BOOL reval=ReadFile(hSvrHndle, rBuf, sizeof(rBuf), &bytesread, NULL); if(reval){ if(bytesread>0){ memcpy(shareBuf,rBuf,sizeof(shareBuf)); CString str; str.Format("%s",shareBuf); UpdateData(TRUE); m_data=str; UpdateData(FALSE); strcpy(rBuf,"Received"); WriteFile(hSvrHndle,rBuf,sizeof(rBuf),&bytesread,NULL); } } else flag=FALSE; } CloseHandle(hSvrHndle); //CDialog::OnOK(); }
客户端
void CPipetest2Dlg::OnOK() { // TODO: Add extra validation here UpdateData(TRUE); if (m_clientdata=="") { AfxMessageBox("content blank!"); return; } UpdateData(FALSE); HANDLE hClient = CreateFile("\\\\.\\pipe\\pipetest\\", GENERIC_WRITE |GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hClient == INVALID_HANDLE_VALUE) { AfxMessageBox("Error open/connect pipe"); } DWORD bytesread=-1; char rBuf[512],shareBuf[512]; LPTSTR lpsz =(LPTSTR)(LPCTSTR)m_clientdata; strcpy(rBuf, lpsz); BOOL reval=WriteFile(hClient,rBuf,sizeof(rBuf),&bytesread,NULL); if(!reval){ AfxMessageBox("Write into pipe error!"); } reval=ReadFile(hClient, rBuf, sizeof(rBuf), &bytesread, NULL); if(reval){ if(bytesread>0){ memcpy(shareBuf,rBuf,sizeof(shareBuf)); CString str; str.Format("%s",shareBuf); UpdateData(TRUE); m_clientdata=str; UpdateData(FALSE); } } CloseHandle(hClient); //CDialog::OnOK(); }