-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpclient.h
97 lines (82 loc) · 1.92 KB
/
tcpclient.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
#ifndef _EVILSOCK_TCP_CLIENT
#define _EVILSOCK_TCP_CLIENT
#include "evilsocket.h"
class TcpClient {
public:
socket_t handle = INVALID_SOCKET;
errno_t error = 0;
int keepalivesec;
bool closed = false;
TcpClient(socket_t handle) : handle{ handle }, error{ 0 }, keepalivesec { 0 } {
if (handle == INVALID_SOCKET) {
set_error(ERROR_INVALID_HANDLE);
}
}
TcpClient(const std::string& host, int port, int keepalivesec): keepalivesec{keepalivesec} {
auto init_res = es_init();
if (init_res != 0) {
set_error(init_res);
return;
}
auto socket = es_connect(host, port, keepalivesec);
if (socket == INVALID_SOCKET) {
set_error(es_last_error());
es_close(socket);
return;
}
error = 0;
closed = false;
handle = socket;
}
TcpClient(const TcpClient& copy) = delete;
TcpClient(TcpClient&& move) noexcept : handle{ move.handle }, error{ move.error } {
move.handle = INVALID_SOCKET;
move.error = 0;
}
~TcpClient() {
es_close(handle);
es_deinit();
}
TcpClient& operator=(const TcpClient& copy) {
throw SocketException("TcpClient cannot be copied");
}
TcpClient& operator=(TcpClient&& move) noexcept {
if (this == &move) return *this;
es_close(handle);
handle = move.handle;
error = move.error;
move.handle = INVALID_SOCKET;
move.error = 0;
move.closed = false;
return *this;
}
size_t write_string(const std::string& string) {
auto res = es_write_string(handle, string);
if (res == 0) {
set_error(es_last_error());
}
return res;
}
std::string recv_string(int limit) {
auto res = es_recv_string(handle, limit);
if (res.empty()) {
set_error(es_last_error());
}
return res;
}
std::string recv_string(char terminator) {
auto res = es_recv_string(handle, terminator);
if (res.empty()) {
set_error(es_last_error());
}
return res;
}
private:
void set_error(errno_t er) {
error = er;
if (er == 10054) {
closed = true;
}
}
};
#endif // guard