-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpserver.h
73 lines (60 loc) · 1.44 KB
/
tcpserver.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
#ifndef _EVILSOCK_TCP_SERVER
#define _EVILSOCK_TCP_SERVER
#include <stdexcept>
#include "evilsocket.h"
#ifndef _EVILSOCK_TCP_CLIENT
class TcpClient;
#endif
class TcpServer {
public:
int port;
socket_t handle = INVALID_SOCKET;
errno_t error = 0;
int keepalivesec;
TcpServer(int port, int keepalivesec) : port{ port }, keepalivesec{ keepalivesec } {
auto init_res = es_init();
if (init_res != 0) {
error = init_res;
return;
}
auto socket = es_listen(port, 1);
if (socket == INVALID_SOCKET) {
error = es_last_error();
es_close(socket);
return;
}
error = 0;
handle = socket;
}
TcpServer(const TcpServer& copy) = delete;
TcpServer(TcpServer&& move) noexcept : port{ move.port }, handle { move.handle }, error{ move.error } {
move.handle = INVALID_SOCKET;
move.error = 0;
}
~TcpServer() {
es_close(handle);
es_deinit();
}
TcpServer& operator=(const TcpServer& copy) {
throw SocketException("TcpServer cannot be copied");
}
TcpServer& operator=(TcpServer&& move) noexcept {
if (this == &move) return *this;
es_close(handle);
handle = move.handle;
error = move.error;
port = move.port;
move.handle = INVALID_SOCKET;
move.error = 0;
return *this;
}
TcpClient* accept_client(bool wait) {
auto [address, client] = es_accept(handle, keepalivesec, wait);
if (client == INVALID_SOCKET) {
error = es_last_error();
return nullptr;
}
return new TcpClient(client);
}
};
#endif // guard