-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPipeServer.cpp
More file actions
104 lines (87 loc) · 2.03 KB
/
PipeServer.cpp
File metadata and controls
104 lines (87 loc) · 2.03 KB
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
#include "PipeServer.h"
CPipeServer::CPipeServer() : m_bStop(FALSE)
{
}
CPipeServer::~CPipeServer()
{
Delete();
}
bool CPipeServer::Create(std::wstring& wstrPipeName)
{
bool nRet = true;
std::wstring wstrPipePath(L"\\\\.\\pipe\\");
wstrPipePath.append(wstrPipeName);
m_strPipeName = wstrPipePath;
m_hPipe = CreateNamedPipeW(wstrPipePath.c_str(),
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
1024 * 16,
1024 * 16,
0,
NULL);
if (m_hPipe == INVALID_HANDLE_VALUE)
{
nRet = false;
}
return nRet;
}
bool CPipeServer::Delete()
{
BOOL bResult = FALSE;
if (m_hPipe)
{
CloseHandle(m_hPipe);
if (0 != DeleteFileW(m_strPipeName.c_str()))
{
// 0이 아닌 경우 삭제에 성공했다.
m_hPipe = NULL;
bResult = TRUE;
}
}
return bResult;
}
void CPipeServer::Start()
{
m_bStop = FALSE;
char buffer[1024] = { 0, };
while (true && FALSE == m_bStop) {
DWORD bytesRead;
if (ReadFile(m_hPipe, buffer, sizeof(buffer), &bytesRead, NULL) && bytesRead)
{
std::vector<BYTE> packet(buffer, buffer + bytesRead);
MessageReceivedCallback(packet);
}
else
{
ErrorHandler();
}
}
}
void CPipeServer::Stop()
{
m_bStop = TRUE;
}
void CPipeServer::SetMessageReceivedCallback(const std::function<void(const std::vector<BYTE>&)>& callback)
{
m_messageReceivedCallback = callback;
}
void CPipeServer::ErrorHandler()
{
const DWORD dwErr = ::GetLastError();
switch (dwErr)
{
case ERROR_PIPE_LISTENING:
case ERROR_BROKEN_PIPE:
DisconnectNamedPipe(m_hPipe);
ConnectNamedPipe(m_hPipe, NULL);
default:
break;
}
}
void CPipeServer::MessageReceivedCallback(const std::vector<BYTE>& packet)
{
if (m_messageReceivedCallback) {
m_messageReceivedCallback(packet);
}
}