-
Notifications
You must be signed in to change notification settings - Fork 1
/
Network.h
88 lines (79 loc) · 1.67 KB
/
Network.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
#pragma once
#include <WinSock2.h>
#include <memory>
#pragma comment(lib, "ws2_32.lib")
#include "Buffer.h"
using namespace std;
class SocketRAII {
private:
SOCKET m_socket;
public:
SocketRAII(SOCKET socket);
SocketRAII(SocketRAII&& socket) noexcept;
~SocketRAII();
void reset(SOCKET socket);
void release();
SocketRAII& operator=(SocketRAII&& other) noexcept;
SOCKET getHandle() const;
};
class SocketException
{
public:
enum E {
DISCONN,
REFUSE,
BUFFER
};
private:
int ecode;
public:
SocketException(int code) : ecode(code) {};
int GetErrorCode() const { return ecode; }
};
class TcpCommunicator
{
private:
SOCKET m_socket;
public:
TcpCommunicator(SOCKET socket);
~TcpCommunicator();
unique_ptr<CBuffer> Receive();
auto Send(const CBuffer& buffer);
void reset(SOCKET socket);
auto getHandle() const {
return m_socket;
}
void Shutdown(int how);
void Close();
};
class TcpListener
{
private:
SOCKET m_socket;
sockaddr_in m_addr;
public:
TcpListener(SOCKET);
~TcpListener();
void SetAddress(const ULONG& address, int port);
void Listen(int backlog);
void Bind();
SOCKET Accept();
SOCKET Accept(ULONG* addr);
void Shutdown(int how);
void Close();
auto getHandle() const {
return m_socket;
}
static SOCKET Accept(SOCKET s, ULONG* addr)
{
sockaddr_in _addr;
int sz = sizeof(sockaddr_in);
auto as = accept(s, (sockaddr*)&_addr, &sz);
*addr = _addr.sin_addr.S_un.S_addr;
return as;
}
};
SOCKET make_tcpSocket();
void Bind(SOCKET s, const ULONG& address, int port);
void PerfectSend(SOCKET s, CBuffer& buffer);
void PerfectRecv(SOCKET s, CBuffer& buffer);