-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhidp_net.h
More file actions
120 lines (103 loc) · 2.44 KB
/
hidp_net.h
File metadata and controls
120 lines (103 loc) · 2.44 KB
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
112
113
114
115
116
117
118
119
120
#pragma once
#include "hidp_common.h"
#include <memory>
#include <string>
#include <sys/socket.h>
class Socket;
class TcpClient;
class TcpListener;
class Socket {
friend class TcpListener;
public:
Socket();
~Socket();
int Read(void *buff, int count);
int Write(const void* buff, int count);
void Bind(const char *addr, int port);
void Connect(const char *addr, int port);
void Close();
inline int GetFD() const;
inline bool IsConnected() const;
private:
Socket(int fd)
: m_fd(fd) { }
void SetRemoteEndpoint(const sockaddr_storage &remote, socklen_t length);
void SetLocalEndpoint(const sockaddr_storage &remote, socklen_t length);
private:
int m_fd;
sockaddr_storage m_remote_endpoint;
socklen_t m_remote_endpoint_length;
sockaddr_storage m_local_endpoint;
socklen_t m_local_endpoint_length;
};
class TcpListener {
public:
TcpListener(const char *addr, int port);
void Start();
std::unique_ptr<Socket> Accept();
inline int GetFD() const;
private:
std::string m_local_addr;
int m_local_port;
Socket m_socket;
};
class TcpClient {
public:
inline int Read(void *buff, int count);
inline int Write(const void* buff, int count);
inline int GetFD() const;
inline Socket& GetSocket();
void Connect(const char *addr, int port);
inline bool IsConnected() const;
private:
Socket m_socket;
};
inline bool TcpClient::IsConnected() const
{
return m_socket.IsConnected();
}
inline int TcpClient::Read(void *buff, int count)
{
return m_socket.Read(buff, count);
}
inline int TcpClient::Write(const void *buff, int count)
{
return m_socket.Write(buff, count);
}
inline int TcpClient::GetFD() const
{
return m_socket.GetFD();
}
inline Socket& TcpClient::GetSocket()
{
return m_socket;
}
inline bool Socket::IsConnected() const
{
return m_fd != -1;
}
inline int TcpListener::GetFD() const
{
return m_socket.GetFD();
}
inline int Socket::GetFD() const
{
return m_fd;
}
template<class T> const T& __ref(const T& obj) { return obj; }
template<class T> const T& __ref(const std::unique_ptr<T> &obj) { return *obj.get(); }
template<class T>
inline bool fd_is_set(fd_set& set, const T& carrier)
{
return FD_ISSET(__ref(carrier).GetFD(), &set);
}
template<class T>
void fd_set_add(fd_set& set, const T& carrier, int *max)
{
int fd = __ref(carrier).GetFD();
if (fd != -1) {
FD_SET(fd, &set);
if (fd > *max)
*max = fd;
}
}