#include "stdafx.h" #include "NamePipeClient.h" using namespace std; void NamePipeClient::OpenNamedPipeInClient() { //等待连接命名管道 if( !WaitNamedPipe(_T("\\\\.\\pipe\\testspipe"), NMPWAIT_WAIT_FOREVER) ) { cout<<"命名管道实例不存在 ..."<< endl<< endl; return; } cout << "成功连接到服务器" << endl; //打开命名管道 hNamedPipe = CreateFile( _T("\\\\.\\pipe\\testspipe"), GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if( INVALID_HANDLE_VALUE == hNamedPipe ) { cout << "打开命名管道失败!!!" << endl << endl; return; } } void NamePipeClient::NamedPipeReadInClient() { char * pReadBuf; DWORD dwRead; pReadBuf = new char[strlen(pStr) + 1]; memset(pReadBuf, 0, strlen(pStr) + 1); //从命名管道中读取数据 if( !ReadFile(hNamedPipe, pReadBuf, strlen(pStr), &dwRead, NULL) ) { delete []pReadBuf; cout << "读取数据失败 ..."<< endl << endl; return; } cout<<"读取数据成功:: "<< pReadBuf << endl << endl; } void NamePipeClient::NamedPipeWriteInClient() { DWORD dwWrite; //向命名管道中写入数据 if( !WriteFile(hNamedPipe, pStr, strlen(pStr), &dwWrite, NULL) ) { cout<<"写入数据失败 ..." << endl << endl; return; } cout<< "写入数据成功:: "<< pStr << endl << endl; } int main() { NamePipeClient pipeclient; pipeclient.OpenNamedPipeInClient(); //往命名管道中写入数据 pipeclient.NamedPipeWriteInClient(); //接收从服务器发来的数据 pipeclient.NamedPipeReadInClient(); system("pause"); return 0; }