-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcp_socket.hpp
136 lines (106 loc) · 3.08 KB
/
tcp_socket.hpp
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
#ifndef VI_TCP_SOCKET_HPP
#define VI_TCP_SOCKET_HPP
#include "common_defs.h"
#include "common_inc.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/unistd.h>
#include <sys/fcntl.h>
#include <arpa/inet.h>
#include <netinet/in.h>
namespace vi
{
class tcp_socket
{
friend class tcp_client;
friend class tcp_server;
public:
enum socket_result
{
ok,
try_again,
error
};
private:
socket_t mSocket;
sockaddr_in mAddress;
public:
tcp_socket() : mSocket(-1)
{
memset(&mAddress, 0, sizeof(mAddress));
}
~tcp_socket()
{
close();
}
bool is_valid() const
{
return mSocket >= 0;
}
tcp_socket& open()
{
mSocket = ::socket(AF_INET, SOCK_STREAM, 0);
assert(mSocket >= 0);
return *this;
}
void close()
{
if (is_valid())
{
::close(mSocket);
mSocket = -1;
}
}
tcp_socket& reuse_address()
{
int reuse = 1;
int result = ::setsockopt(mSocket, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));
assert(0 == result);
return *this;
}
tcp_socket& set_nonblocking()
{
int flags = ::fcntl(mSocket, F_GETFL, 0);
if (-1 == flags)
{
flags = 0;
}
int result = ::fcntl(mSocket, F_SETFL, flags | O_NONBLOCK);
assert(0 == result);
return *this;
}
tcp_socket& bind_and_listen(const char* address, uint16_t port, uint16_t queueSize)
{
mAddress.sin_family = AF_INET;
mAddress.sin_addr.s_addr = ::inet_addr(address);;
mAddress.sin_port = htons(port);
int result = ::bind(mSocket, reinterpret_cast<const sockaddr*>(&mAddress), sizeof(mAddress));
assert(0 == result);
result = ::listen(mSocket, queueSize);
assert(0 == result);
return *this;
}
tcp_socket::socket_result connect(const char* address, uint16_t port)
{
mAddress.sin_family = AF_INET;
mAddress.sin_addr.s_addr = ::inet_addr(address);;
mAddress.sin_port = ::htons(port);
int result = ::connect(mSocket, reinterpret_cast<const sockaddr*>(&mAddress), sizeof(mAddress));
return (0 == result) ? tcp_socket::ok : tcp_socket::error;
}
tcp_socket::socket_result accept(tcp_socket& s)
{
socklen_t addrSize = sizeof(s.mAddress);
s.mSocket = ::accept(mSocket, reinterpret_cast<sockaddr*>(&mAddress), &addrSize);
if (s.mSocket < 0)
{
return (EWOULDBLOCK == errno) ? tcp_socket::try_again : tcp_socket::error;
}
else
{
return tcp_socket::ok;
}
}
};
};
#endif