-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNamedPipeServer.cpp
108 lines (101 loc) · 2.13 KB
/
NamedPipeServer.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include "NamedPipeServer.h"
#include <iostream>
CNamedPipeServer::CNamedPipeServer()
{
hEvent_ = CreateEvent(NULL, FALSE, FALSE, NULL);
if(!hEvent_)
{
std::cout<<"Create event failed!"<<std::endl;
}
}
CNamedPipeServer::~CNamedPipeServer(void)
{
if (hPipe_)
{
CloseHandle(hPipe_);
}
if (hEvent_)
{
CloseHandle(hEvent_);
}
}
bool CNamedPipeServer::Create(const char * szPipName)
{
pipeName_ = szPipName;
return true;
}
bool CNamedPipeServer::Listen()
{
OVERLAPPED ovlpd;
while (true)
{
hPipe_ = CreateNamedPipe(
pipeName_.c_str(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
0,
1,
1024,
1024,
0,
NULL
);
if(INVALID_HANDLE_VALUE == hPipe_)
{
std::cout<<"Create namedPipe failed!"<<std::endl;
hPipe_ = NULL;
return false;
}
memset(&ovlpd, 0, sizeof(OVERLAPPED));
ovlpd.hEvent = hEvent_;
if(!ConnectNamedPipe(hPipe_, &ovlpd))
{
if(ERROR_IO_PENDING != GetLastError())
{
std::cout<<"ConnectNamedPipe failed!"<<std::endl;
return false;
}
}
if(WAIT_FAILED == WaitForSingleObject(hEvent_, INFINITE))
{
std::cout<<"WaitForSingleObject failed!"<<std::endl;
return false;
}
DWORD dwRead;
char * pReadBuf = new char[BUFSIZE + 1];
memset(pReadBuf, 0,BUFSIZE + 1);
if(!ReadFile(hPipe_, pReadBuf,BUFSIZE, &dwRead, NULL))
{
delete[] pReadBuf;
std::cout<<"ReadFile failed!"<<std::endl;
return false;
}
std::string cmd(pReadBuf,dwRead);
delete []pReadBuf;
std::string result = Process(cmd.c_str());
DWORD dwWrite;
if(!WriteFile(hPipe_, result.c_str(), result.length(), &dwWrite, NULL))
{
std::cout<<"WriteFile failed!"<<std::endl;
return false;
}
CloseHandle(hPipe_);
hPipe_ = NULL;
}
return true;
}
std::string CNamedPipeServer::Process(const char * cmd)
{
std::string result = std::string(cmd) + ":OK";
Sleep(10000);
std::cout<<"receive:"<<cmd<<std::endl;
std::cout<<"return:"<<result.c_str()<<std::endl;
return result;
}
bool CNamedPipeServer::Stop()
{
return false;
}
bool CNamedPipeServer::Close()
{
return false;
}