-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathipcpp.cpp
107 lines (96 loc) · 2.9 KB
/
ipcpp.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
#include <Windows.h>
#include <string>
// or paste `ipc.h` and `ipc.c`'s code here.
#include "ipc.h"
extern "C" {
#include "ipc.c"
};
#include "ipcpp.h"
namespace dipc
{
mutex::mutex() {};
mutex::~mutex() {};
void mutex::lock() {
while(this->interlock_ == 1
|| InterlockedCompareExchange(&this->interlock_, 1, 0) == 1) {
Sleep(1);
}
}
void mutex::unlock() {
this->interlock_ = 0;
}
locker::locker(mutex& m): m_(m) {
m_.lock();
}
locker::~locker() {
m_.unlock();
}
server::server(const std::tstring& name, int timeout) :
data_(NULL), stop_(false), routers_() {
do {
data_ = ServerCreate(name.c_str());
if (data_) {
data_->timeout = timeout;
}
} while (false);
}
server::~server() {
ServerClose(data_);
}
void server::run() {
if (!data_) {
return;
}
stop_ = false;
while(!stop_) {
ServerReady(data_);
if (ServerWaitForRequst(data_)) {
CommPacket* packet = (CommPacket*)data_->buf;
std::vector<router>::size_type i = 0;
for (; i < routers_.size(); i++)
{
if (routers_[i].cmd == packet->cmd) {
packet->size = routers_[i].handler((unsigned char*)packet->data, packet->size - sizeof(CommPacket)) + sizeof(CommPacket);
break;
}
}
if (i == routers_.size()) {
packet->cmd = -1;
packet->size = sizeof(CommPacket);
}
ServerReplied(data_);
ServerWaitClientDone(data_);
}
}
}
void server::stop() { stop_ = true; }
void server::route(int cmd, std::function<int(unsigned char*, int)> handler) {
locker l(this->mr_);
std::vector<router>::iterator it = routers_.begin();
for (; it != routers_.end(); it++)
{
if (it->cmd == cmd) {
it->handler = handler;
break;
}
}
if (it == routers_.end()) {
router r = {cmd, handler};
routers_.push_back(r);
}
}
client::client(const std::tstring& server_name, int timeout) :
server_name(server_name), timeout(timeout) { }
client::~client() { }
std::string client::request(int cmd, const std::string& data) {
std::string ret;
CommPacket* packet = ClientRequest(cmd, (const unsigned char*)data.c_str(), data.size(), server_name.c_str(), timeout);
if (packet) {
if (packet->cmd == cmd) {
ret.insert(ret.begin(), (unsigned char*)packet->data, (unsigned char*)packet + packet->size);
}
FreePacket(packet);
}
return ret;
}
}