-
Notifications
You must be signed in to change notification settings - Fork 2
/
PipeServer.cpp
86 lines (73 loc) · 1.94 KB
/
PipeServer.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
#include "stdafx.h"
#include "PipeServer.h"
#include "Common.h"
#include "Pipe.h"
#define BUFSIZE (1 * 1024)
PipeServer::PipeServer(const std::string &name, DWORD milliseconds)
: milliseconds_(milliseconds), serverPipe_(INVALID_HANDLE_VALUE)
{
pipeName_ = Common::toString("\\\\.\\pipe\\%s", name.c_str());
createServerPipe();
}
PipeServer::~PipeServer(void)
{
close();
}
NamedPipe* PipeServer::accept()
{
if (serverPipe_ == INVALID_HANDLE_VALUE) {
createServerPipe();
}
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(OVERLAPPED));
overlapped.hEvent = winEvent_.getHandle();
if (ConnectNamedPipe(serverPipe_, &overlapped)) {
std::string errString = "ConnectNamedPipe failed, " + Common::getErrString();
throw Exception(errString);
} else {
int errCode = GetLastError();
switch (errCode) {
case ERROR_PIPE_CONNECTED:
break;
case ERROR_IO_PENDING:
winEvent_.waitForEvent(milliseconds_);
DWORD cbRet;
if (!GetOverlappedResult(serverPipe_, &overlapped, &cbRet, FALSE)) {
std::string errString = "ConnectNamedPipe failed, after GetOverlappedResult, " + Common::getErrString();
throw Exception(errString);
}
break;
default:
std::string errString = "ConnectNamedPipe failed, " + Common::getErrString();
throw Exception(errString);
}
}
NamedPipe *result = new NamedPipe(serverPipe_, true);
serverPipe_ = INVALID_HANDLE_VALUE;
return result;
}
void PipeServer::close()
{
winEvent_.notify();
}
void PipeServer::waitForConnect(DWORD milliseconds)
{
}
void PipeServer::closeConnection()
{
}
void PipeServer::createServerPipe()
{
serverPipe_ = CreateNamedPipe(Common::ansi2unicode(pipeName_).c_str(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
BUFSIZE,
BUFSIZE,
0,
0);
if (serverPipe_ == INVALID_HANDLE_VALUE) {
std::string errString = "CreateNamedPipe failed, " + Common::getErrString();
throw Exception(errString);
}
}