-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathServer.cc
208 lines (160 loc) · 5.77 KB
/
Server.cc
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#include "ClientSocket.hh"
#include "Server.hh"
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <algorithm>
#include <future>
#include <memory>
#include <stdexcept>
#include <string>
Server::~Server()
{
this->close();
}
void Server::setBacklog( int backlog )
{
_backlog = backlog;
}
void Server::setPort( int port )
{
_port = port;
}
void Server::close()
{
if( _socket )
::close( _socket );
for( auto&& clientSocket : _clientSockets )
clientSocket->close();
_clientSockets.clear();
}
void Server::listen()
{
_socket = socket( AF_INET, SOCK_STREAM, 0 );
if( _socket == -1 )
throw std::runtime_error( std::string( strerror( errno ) ) );
{
int option = 1;
setsockopt( _socket,
SOL_SOCKET,
SO_REUSEADDR,
reinterpret_cast<const void*>( &option ),
sizeof( option ) );
}
sockaddr_in socketAddress;
std::fill( reinterpret_cast<char*>( &socketAddress ),
reinterpret_cast<char*>( &socketAddress ) + sizeof( socketAddress ),
0 );
socketAddress.sin_family = AF_INET;
socketAddress.sin_addr.s_addr = htonl( INADDR_ANY );
socketAddress.sin_port = htons( _port );
{
int result = bind( _socket,
reinterpret_cast<const sockaddr*>( &socketAddress ),
sizeof( socketAddress ) );
if( result == -1 )
throw std::runtime_error( std::string( strerror( errno ) ) );
}
{
int result = ::listen( _socket, _backlog );
if( result == -1 )
throw std::runtime_error( std::string( strerror( errno ) ) );
}
fd_set masterSocketSet;
fd_set clientSocketSet;
FD_ZERO( &masterSocketSet );
FD_SET( _socket, &masterSocketSet );
int highestFileDescriptor = _socket;
while( 1 )
{
clientSocketSet = masterSocketSet;
int numFileDescriptors = select( highestFileDescriptor + 1,
&clientSocketSet,
nullptr, // no descriptors to write into
nullptr, // no descriptors with exceptions
nullptr ); // no timeout
if( numFileDescriptors == -1 )
break;
// Will be updated in the loop as soon as a new client has been
// accepted. This saves us from modifying the variable *during*
// the loop execution.
int newHighestFileDescriptor = highestFileDescriptor;
for( int i = 0; i <= highestFileDescriptor; i++ )
{
if( !FD_ISSET( i, &clientSocketSet ) )
continue;
// Handle new client
if( i == _socket )
{
sockaddr_in clientAddress;
auto clientAddressLength = sizeof(clientAddress);
int clientFileDescriptor = accept( _socket,
reinterpret_cast<sockaddr*>( &clientAddress ),
reinterpret_cast<socklen_t*>( &clientAddressLength ) );
if( clientFileDescriptor == -1 )
break;
FD_SET( clientFileDescriptor, &masterSocketSet );
newHighestFileDescriptor = std::max( highestFileDescriptor, clientFileDescriptor );
auto clientSocket = std::make_shared<ClientSocket>( clientFileDescriptor, *this );
if( _handleAccept )
auto result = std::async( std::launch::async, _handleAccept, clientSocket );
_clientSockets.push_back( clientSocket );
}
// Known client socket
else
{
char buffer[2] = {0,0};
// Let's attempt to read at least one byte from the connection, but
// without removing it from the queue. That way, the server can see
// whether a client has closed the connection.
int result = recv( i, buffer, 1, MSG_PEEK );
if( result <= 0 )
{
// It would be easier to use erase-remove here, but this leads
// to a deadlock. Instead, the current socket will be added to
// the list of stale sockets and be closed later on.
this->close( i );
}
else
{
auto itSocket = std::find_if( _clientSockets.begin(), _clientSockets.end(),
[&] ( std::shared_ptr<ClientSocket> socket )
{
return socket->fileDescriptor() == i;
} );
if( itSocket != _clientSockets.end() && _handleRead )
auto result = std::async( std::launch::async, _handleRead, *itSocket );
}
}
}
// Update the file descriptor if a new client has been accepted in
// the loop above.
highestFileDescriptor = std::max( newHighestFileDescriptor, highestFileDescriptor );
// Handle stale connections. This is in an extra scope so that the
// lock guard unlocks the mutex automatically.
{
std::lock_guard<std::mutex> lock( _staleFileDescriptorsMutex );
for( auto&& fileDescriptor : _staleFileDescriptors )
{
FD_CLR( fileDescriptor, &masterSocketSet );
::close( fileDescriptor );
}
_staleFileDescriptors.clear();
}
}
}
void Server::close( int fileDescriptor )
{
std::lock_guard<std::mutex> lock( _staleFileDescriptorsMutex );
_clientSockets.erase( std::remove_if( _clientSockets.begin(), _clientSockets.end(),
[&] ( std::shared_ptr<ClientSocket> socket )
{
return socket->fileDescriptor() == fileDescriptor;
} ),
_clientSockets.end() );
_staleFileDescriptors.push_back( fileDescriptor );
}