-
Notifications
You must be signed in to change notification settings - Fork 0
/
MsgOpt.cpp
111 lines (92 loc) · 2.65 KB
/
MsgOpt.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
109
110
111
#include "MsgOpt.h"
bool EvtOpt::Create(string name) {
_hEvent = CreateEvent(NULL, FALSE, FALSE, name.c_str());
return _hEvent != NULL;
}
bool EvtOpt::Connect(string name) {
_hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, name.c_str());
return _hEvent != NULL;
}
bool EvtOpt::Wait(DWORD time /*= INFINITE*/) {
if (_hEvent) WaitForSingleObject(_hEvent, time);
return true;
}
bool EvtOpt::Signal() {
if (_hEvent) SetEvent(_hEvent);
return true;
}
bool EvtOpt::Uninit() {
if (_hEvent) {
SetEvent(_hEvent);
CloseHandle(_hEvent);
_hEvent = NULL;
}
return true;
}
bool MsgOpt::Listen(string name) {
string strName = "Local\\" + name;
if (!_evtOpt.Connect(strName.c_str())) {
_evtOpt.Create(strName.c_str());
}
if (!_evtOpt.Connect(strName.c_str())) return false;
_evtOpt.Wait();
_hMapFile = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE,
(strName + "_map").c_str());
if (_hMapFile == NULL) return false;
_pBuf = (LPTSTR)MapViewOfFile(_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, _bufSize);
if (!_pBuf) return false;
if (_onRcvMsg) _onRcvMsg(*((MsgStruct*)_pBuf));
return true;
}
bool MsgOpt::Connect(string name) {
string strName = "Local\\" + name;
if (!_evtOpt.Connect(strName.c_str())) {
_evtOpt.Create(strName.c_str());
}
if (!_evtOpt.Connect(strName.c_str())) return false;
_hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE, 0, _bufSize, (strName+"_map").c_str());
if (_hMapFile == NULL) return false;
_pBuf = (LPTSTR)MapViewOfFile(_hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, _bufSize);
_evtOpt.Signal();
return _pBuf != NULL;
}
bool MsgOpt::Uninit() {
_exited = true;
_evtOpt.Uninit();
if (_pBuf){
UnmapViewOfFile(_pBuf);
_pBuf = NULL;
}
if (_hMapFile) {
CloseHandle(_hMapFile);
_hMapFile = NULL;
}
return true;
}
bool MsgOpt::WaitMsg(int time /*= INFINITE*/) {
if (_exited) return false;
_evtOpt.Wait(time);
if (_onRcvMsg) _onRcvMsg(*((MsgStruct*)_pBuf));
return true;
}
bool MsgOpt::PostMsg(MsgStruct& msg) {
if (_pBuf) memcpy_s((void*)_pBuf, _bufSize, &msg, sizeof(msg));
_evtOpt.Signal();
return true;
}
bool MsgMgr::Create(string name, bool main) {
return _msgClient.Connect(name + (main ? "" : "_main")) &&
_msgSvr.Listen(name + (main ? "_main" : ""));
}
bool MsgMgr::WaitMsg(int time /*= INFINITE*/) {
return _msgSvr.WaitMsg();
}
bool MsgMgr::PostMsg(MsgStruct& msg) {
return _msgClient.PostMsg(msg);
}
bool MsgMgr::Destroy() {
_msgClient.Uninit();
_msgSvr.Uninit();
return true;
}