123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- #include "stdafx.h"
- #include "NamePipeServer.h"
- using namespace std;
- void NamePipeServer::CreateNamedPipeInServer()
- {
- HANDLE hEvent;
- OVERLAPPED ovlpd;
- BYTE sd[SECURITY_DESCRIPTOR_MIN_LENGTH];
- SECURITY_ATTRIBUTES sa;
- sa.nLength = sizeof(SECURITY_ATTRIBUTES);
- sa.bInheritHandle = TRUE;
- sa.lpSecurityDescriptor = &sd;
- InitializeSecurityDescriptor(&sd, SECURITY_DESCRIPTOR_REVISION);
- SetSecurityDescriptorDacl(&sd, TRUE, (PACL) 0, FALSE);
- //创建命名管道
- //这里创建的是双向模式且使用重叠模式(异步操作)的命名管道
- hNamedPipe = CreateNamedPipe( _T("\\\\.\\pipe\\testspipe"), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,0, 1, 1024, 1024, 0, &sa);
- if( INVALID_HANDLE_VALUE == hNamedPipe )
- {
- cout << GetLastError() << endl;
- hNamedPipe = NULL;
- cout << "创建命名管道失败!!!" << endl << endl;
- return;
- }
- hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
- if( !hEvent )
- {
- cout<<"创建事件失败 ..."<< endl<< endl;
- return;
- }
- memset(&ovlpd, 0, sizeof(OVERLAPPED));
- ovlpd.hEvent = hEvent;
- cout << "等待客户端的连接" << endl;
- if( !ConnectNamedPipe(hNamedPipe, &ovlpd) )
- {
- if( ERROR_IO_PENDING != GetLastError() )
- {
- CloseHandle(hNamedPipe);
- CloseHandle(hEvent);
- cout<<"等待客户端连接失败 ..."<< endl << endl;
- return;
- }
- }
- //等待事件 hEvent 失败
- if( WAIT_FAILED == WaitForSingleObject(hEvent, INFINITE) )
- {
- CloseHandle(hNamedPipe);
- CloseHandle(hEvent);
- cout<<"等待对象失败 ..."<<endl<<endl;
- return;
- }
- CloseHandle(hEvent);
- }
- void NamePipeServer::NamedPipeReadInServer()
- {
- 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 NamePipeServer::NamedPipeWriteInServer()
- {
- DWORD dwWrite;
- //向命名管道中写入数据
- if( !WriteFile(hNamedPipe, pStr, strlen(pStr), &dwWrite, NULL) )
- {
- cout << "写入数据失败 ..." << endl<< endl;
- return;
- }
- cout << "写入数据成功:: "<< pStr<< endl<< endl;
- }
- int main()
- {
- NamePipeServer pipeserver;
- //创建命名管道
- pipeserver.CreateNamedPipeInServer();
- //从命名管道读数据
- pipeserver.NamedPipeReadInServer();
- //向匿名管道中写入数据
- pipeserver.NamedPipeWriteInServer();
- system("pause");
- return 0;
- }
|