-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.h
105 lines (92 loc) · 2.29 KB
/
client.h
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
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include "common.h"
#include "serialization.h"
using std::string;
void sendHeader(HANDLE h, string key);
bool awaitSendSuccess(HANDLE h);
template <class T>
void send(string key, T data) {
HANDLE h{ INVALID_HANDLE_VALUE };
while (h == INVALID_HANDLE_VALUE) {
h = CreateFile(
pipeName,
GENERIC_READ | GENERIC_WRITE,
0,
nullptr,
OPEN_EXISTING,
0,
nullptr
);
if (h == INVALID_HANDLE_VALUE) {
auto e = GetLastError();
if (e != ERROR_PIPE_BUSY) {
cout << "0x" << hex << GetLastError() << endl;
throw "Couldn't connect.";
}
// server hasnt yet made another instance for additional clients
// so wait then try again
auto instanceReady{ WaitNamedPipe(pipeName, NMPWAIT_WAIT_FOREVER) };
if (!instanceReady) {
cout << "Couldn't connect: 0x" << hex << GetLastError() << endl;
throw "Couldn't connect.";
}
}
}
DWORD mode{ PIPE_READMODE_MESSAGE };
auto modeSet = SetNamedPipeHandleState(
h, // pipe handle
&mode, // new pipe mode
nullptr, // don't set maximum bytes
nullptr); // don't set maximum time
if (!modeSet) {
throw "Couldn't put pipe into message mode.";
}
sendHeader(h, key);
sendData(h, data);
const bool success = awaitSendSuccess(h);
CloseHandle(h);
log(string{ "Send " } + (success ? "success" : "fail"));
}
template<class T>
T get(string key) {
log("Getting data for key " + key);
auto headerData{ serialize(Action { Type::Get, key }) };
vector<char> buf(bufSize);
DWORD bytesRead;
const bool success = CallNamedPipe(
pipeName,
&headerData[0],
headerData.size(),
buf.data(),
buf.size(),
&bytesRead,
NMPWAIT_WAIT_FOREVER
);
if (!success) {
throw GetLastError();
}
log("Got data for key " + key);
auto data{ deserialize<T>(string{buf.data(), bytesRead}) };
return data;
}
template<class T>
void sendData(HANDLE h, T data) {
log("Sending data");
auto writeStr{ serialize(data) };
DWORD bytesWritten{ 0 };
const bool success = WriteFile(
h,
&writeStr[0],
writeStr.size(),
&bytesWritten,
nullptr
);
if (!success) {
cout << "0x" << hex << GetLastError() << endl;
throw GetLastError();
}
log("Sent data");
}