NamePipeClient.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "stdafx.h"
  2. #include "NamePipeClient.h"
  3. using namespace std;
  4. void NamePipeClient::OpenNamedPipeInClient()
  5. {
  6. //等待连接命名管道
  7. if( !WaitNamedPipe(_T("\\\\.\\pipe\\testspipe"), NMPWAIT_WAIT_FOREVER) )
  8. {
  9. cout<<"命名管道实例不存在 ..."<< endl<< endl;
  10. return;
  11. }
  12. cout << "成功连接到服务器" << endl;
  13. //打开命名管道
  14. hNamedPipe = CreateFile( _T("\\\\.\\pipe\\testspipe"), GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
  15. if( INVALID_HANDLE_VALUE == hNamedPipe )
  16. {
  17. cout << "打开命名管道失败!!!" << endl << endl;
  18. return;
  19. }
  20. }
  21. void NamePipeClient::NamedPipeReadInClient()
  22. {
  23. char * pReadBuf;
  24. DWORD dwRead;
  25. pReadBuf = new char[strlen(pStr) + 1];
  26. memset(pReadBuf, 0, strlen(pStr) + 1);
  27. //从命名管道中读取数据
  28. if( !ReadFile(hNamedPipe, pReadBuf, strlen(pStr), &dwRead, NULL) )
  29. {
  30. delete []pReadBuf;
  31. cout << "读取数据失败 ..."<< endl << endl;
  32. return;
  33. }
  34. cout<<"读取数据成功:: "<< pReadBuf << endl << endl;
  35. }
  36. void NamePipeClient::NamedPipeWriteInClient()
  37. {
  38. DWORD dwWrite;
  39. //向命名管道中写入数据
  40. if( !WriteFile(hNamedPipe, pStr, strlen(pStr), &dwWrite, NULL) )
  41. {
  42. cout<<"写入数据失败 ..." << endl << endl;
  43. return;
  44. }
  45. cout<< "写入数据成功:: "<< pStr << endl << endl;
  46. }
  47. int main()
  48. {
  49. NamePipeClient pipeclient;
  50. pipeclient.OpenNamedPipeInClient();
  51. //往命名管道中写入数据
  52. pipeclient.NamedPipeWriteInClient();
  53. //接收从服务器发来的数据
  54. pipeclient.NamedPipeReadInClient();
  55. system("pause");
  56. return 0;
  57. }