forked from embeddedmz/socket-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPServer.cpp
More file actions
383 lines (330 loc) · 12.4 KB
/
TCPServer.cpp
File metadata and controls
383 lines (330 loc) · 12.4 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
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/**
* @file TCPServer.cpp
* @brief implementation of the TCP server class
* @author Mohamed Amine Mzoughi <[email protected]>
*/
#include "TCPServer.h"
CTCPServer::CTCPServer(const LogFnCallback oLogger,
/*const std::string& strAddr,*/ const std::string& strPort,
const SettingsFlag eSettings /*= ALL_FLAGS*/) /*throw (EResolveError)*/
: ASocket(oLogger, eSettings)
, m_ListenSocket(INVALID_SOCKET)
//, m_strHost(strAddr)
, m_strPort(strPort)
, m_pResultAddrInfo(nullptr)
, m_HintsAddrInfo()
{
}
CTCPServer::~CTCPServer()
{
SocketClose(m_ListenSocket);
}
bool CTCPServer::InitAddrInfo()
{
// Resolve the server address and port
memset(&m_HintsAddrInfo, 0, sizeof(m_HintsAddrInfo));
/* AF_INET is used to specify the IPv4 address family. */
m_HintsAddrInfo.ai_family = AF_INET;
/* SOCK_STREAM is used to specify a stream socket. */
m_HintsAddrInfo.ai_socktype = SOCK_STREAM;
/* IPPROTO_TCP is used to specify the TCP protocol. */
m_HintsAddrInfo.ai_protocol = IPPROTO_TCP;
/* AI_PASSIVE flag indicates the caller intends to use the returned socket
* address structure in a call to the bind function.*/
m_HintsAddrInfo.ai_flags = AI_PASSIVE;
int iResult = getaddrinfo(nullptr, m_strPort.c_str(), &m_HintsAddrInfo, &m_pResultAddrInfo);
if (iResult != 0)
{
SocketLog("[ERROR]TCPServer, getaddrinfo failed[%s:%s][:%s]", iResult, GaiStrerror(iResult), m_strPort.c_str());
return false;
}
return true;
}
// Method for setting receive timeout. Can be called after Listen, using the previously created ClientSocket
bool CTCPServer::SetRcvTimeout(Socket ClientSocket, unsigned int msec_timeout)
{
bool ret_val = ASocket::SetRcvTimeout(ClientSocket, msec_timeout);
if (!ret_val)
{
SocketLog("[ERROR]TCPServer, setsockopt SOL_SOCKET SO_RCVTIMEO failed[%d:%s][%d][%u]", GetSocketError(), strerror(GetSocketError()), ClientSocket, msec_timeout);
}
return ret_val;
}
#ifndef _WIN32
bool CTCPServer::SetRcvTimeout(Socket ClientSocket, struct timeval timeout)
{
bool ret_val = ASocket::SetRcvTimeout(ClientSocket, timeout);
if (!ret_val)
{
SocketLog("[ERROR]TCPServer, setsockopt SOL_SOCKET SO_RCVTIMEO failed[%d:%s][%d][%u:%u]", GetSocketError(), strerror(GetSocketError()), ClientSocket, timeout.tv_sec, timeout.tv_usec);
}
return ret_val;
}
#endif
// Method for setting send timeout. Can be called after Listen, using the previously created ClientSocket
bool CTCPServer::SetSndTimeout(Socket ClientSocket, unsigned int msec_timeout)
{
bool ret_val = ASocket::SetSndTimeout(ClientSocket, msec_timeout);
if (!ret_val)
{
SocketLog("[ERROR]TCPServer, setsockopt SOL_SOCKET SO_SNDTIMEO failed[%d:%s][%d][%u]", GetSocketError(), strerror(GetSocketError()), ClientSocket, msec_timeout);
}
return ret_val;
}
#ifndef _WIN32
bool CTCPServer::SetSndTimeout(Socket ClientSocket, struct timeval timeout)
{
bool ret_val = ASocket::SetSndTimeout(ClientSocket, timeout);
if (!ret_val)
{
SocketLog("[ERROR]TCPServer, setsockopt SOL_SOCKET SO_SNDTIMEO failed[%d:%s][%d][%u:%u]", GetSocketError(), strerror(GetSocketError()), ClientSocket, timeout.tv_sec, timeout.tv_usec);
}
return ret_val;
}
#endif
// returns the socket of the accepted client
// maxRcvTime and maxSendTime define timeouts in µs for receiving and sending over the socket. Using a negative value
// will deactivate the timeout. 0 will set a zero timeout.
int CTCPServer::Listen(Socket& ClientSocket, size_t msec /*= ACCEPT_WAIT_INF_DELAY*/)
{
ClientSocket = INVALID_SOCKET;
bool isOK = false;
// creates a socket to listen for incoming client connections if it doesn't already exist
if (m_ListenSocket == INVALID_SOCKET)
{
if (m_pResultAddrInfo == nullptr && !InitAddrInfo())
{
return -1;
}
do
{
m_ListenSocket = socket(m_pResultAddrInfo->ai_family, m_pResultAddrInfo->ai_socktype, m_pResultAddrInfo->ai_protocol);
if (m_ListenSocket == INVALID_SOCKET)
{
SocketLog("[ERROR]TCPServer, create socket failed[%d:%s]", GetSocketError(), strerror(GetSocketError()));
break;
}
// Allow the socket to be bound to an address that is already in use
int opt = 1;
if (setsockopt(m_ListenSocket, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char*>(&opt), sizeof(opt)) == SOCKET_ERROR)
{
SocketLog("[ERROR]TCPServer, setsockopt SOL_SOCKET SO_REUSEADDR failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), m_ListenSocket);
break;
}
#if 0
#ifdef SO_KEEPALIVE
if (setsockopt(m_ListenSocket, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast<char*>(&opt), sizeof(opt)) == SOCKET_ERROR)
{
SocketLog("[ERROR]TCPServer, setsockopt SOL_SOCKET SO_KEEPALIVE failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), m_ListenSocket);
break;
}
#endif
#endif
// bind the listen socket to the host address:port
if (bind(m_ListenSocket, m_pResultAddrInfo->ai_addr, static_cast<int>(m_pResultAddrInfo->ai_addrlen)) == SOCKET_ERROR)
{
SocketLog("[ERROR]TCPServer, bind failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), m_ListenSocket);
break;
}
// This listen() call tells the socket to listen to the incoming connections.
// The listen() function places all incoming connection into a backlog queue
// until accept() call accepts the connection.
// Here, we set the maximum size for the backlog queue to SOMAXCONN.
/* SOMAXCONN = allow max number of connexions in waiting */
if (listen(m_ListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
SocketLog("[ERROR]TCPServer, listen failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), m_ListenSocket);
break;
}
SocketLog("[INFO ]TCPServer, listen succeed[%d]", m_ListenSocket);
isOK = true;
} while (0);
// free memory allocated by getaddrinfo
//if (m_pResultAddrInfo != nullptr)
{
freeaddrinfo(m_pResultAddrInfo);
m_pResultAddrInfo = nullptr;
}
if (!isOK/* && m_ListenSocket != INVALID_SOCKET*/)
{
SocketClose(m_ListenSocket);
return -1;
}
}
do
{
//if (msec != ACCEPT_WAIT_INF_DELAY)
{
int ret = SelectSocket(m_ListenSocket, msec);
if (ret == SOCKET_ERROR)
{
SocketLog("[ERROR]TCPServer, select failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), m_ListenSocket);
break;
}
if (ret == 0)
{
//SocketLog("[INFO ]TCPServer, select timeout[%d]", m_ListenSocket);
return 0;
}
}
// This accept() function will write the connecting client's address info
// into the the address structure and the size of that structure is uClientLen.
// The accept() returns a new socket file descriptor for the accepted connection.
// So, the original socket file descriptor can continue to be used
// for accepting new connections while the new socker file descriptor is used for
// communicating with the connected client.
// accept client connection, the returned socket will be used for I/O operations
sockaddr addrClient{};
int iAddrLen = (int)sizeof(addrClient);
ClientSocket = accept(m_ListenSocket, &addrClient, &iAddrLen);
if (ClientSocket == INVALID_SOCKET)
{
int iErrCode = GetSocketError();
if (SOCKET_ERR_ACCEPT_RETRIABLE(iErrCode))
{
return 0;
}
SocketLog("[ERROR]TCPServer, accept failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), m_ListenSocket);
break;
}
#if 0
{
SocketLog("[INFO ]TCPServer, Incoming connection from[%s:%u]",
(addrClient.sa_family == AF_INET) ? inet_ntoa(((struct sockaddr_in*)&addrClient)->sin_addr) : "",
(addrClient.sa_family == AF_INET) ? ntohs(((struct sockaddr_in*)&addrClient)->sin_port) : 0);
}
#endif
#if 0
char buf1[256] = {};
unsigned long len2 = 256UL;
if (WSAAddressToStringA(&addrClient, lenAddr, NULL, buf1, &len2) != SOCKET_ERROR)
{
SocketLog("[INFO ]TCPServer, Connection from[%s]", buf1);
}
#endif
SocketLog("[INFO ]TCPServer, client_sock be accepted[%d]", ClientSocket);
return 1;
} while (0);
SocketClose(m_ListenSocket);
return -1;
}
/* ret > 0 : bytes received
* ret == 0 : connection closed
* ret < 0 : recv failed
*/
int CTCPServer::Receive(Socket ClientSocket, char* pData, size_t uSize, bool bReadFully /*= true*/) const
{
if (ClientSocket == INVALID_SOCKET)
{
SocketLog("[ERROR]TCPServer, recv failed[not a connection to server.]");
return -1;
}
if (pData == nullptr || uSize == 0)
{
SocketLog("[ERROR]TCPServer, recv failed[%d][%p:%zu]", ClientSocket, pData, uSize);
return -2;
}
#if 0
#ifdef _WIN32
int tries = 0;
#endif
#endif
int total = 0;
do
{
int nRecvd = recv(ClientSocket, pData + total, (int)uSize - total, 0);
if (nRecvd == SOCKET_ERROR)
{
int iErrCode = GetSocketError();
if (SOCKET_ERR_RW_RETRIABLE(iErrCode))
{
continue;
}
#if 0
#ifdef _WIN32
// On long messages, Windows recv sometimes fails with WSAENOBUFS, but
// will work if you try again.
if (WSAGetLastError() == WSAENOBUFS && (tries++ < 1000))
{
Sleep(1);
continue;
}
#endif
#endif
if (total == 0)
{
SocketLog("[ERROR]TCPServer, recv failed[%d:%s][%d]", iErrCode, strerror(iErrCode), ClientSocket);
return -1;
}
break;
}
if (nRecvd == 0)
{
if (total == 0)
{
SocketLog("[INFO ]TCPServer, peer shut down[%d]", ClientSocket);
return 0;
}
break;
}
total += nRecvd;
} while (bReadFully && (total < (int)uSize));
return total;
}
int CTCPServer::Send(const Socket ClientSocket, const char* pData, size_t uSize) const
{
if (ClientSocket == INVALID_SOCKET)
{
SocketLog("[ERROR]TCPServer, send failed[not a connection to server.]");
return -1;
}
if (pData == nullptr && uSize != 0)
{
SocketLog("[ERROR]TCPServer, send failed[%d][%p:%zu]", ClientSocket, pData, uSize);
return 0;
}
int total = 0;
do
{
int nSent = send(ClientSocket, pData + total, (int)uSize - total, 0);
if (nSent == SOCKET_ERROR)
{
int iErrCode = GetSocketError();
if (SOCKET_ERR_RW_RETRIABLE(iErrCode))
{
continue;
}
if (SOCKET_ERR_EPIPE(iErrCode))
{
//SocketLog("[WARN ]TCPServer, send shutdowned SHUT_WR[%d:%s][%d]", iErrCode, strerror(iErrCode), ClientSocket);
break;
}
SocketLog("[ERROR]TCPServer, send failed[%d:%s][%d]", iErrCode, strerror(iErrCode), ClientSocket);
return -1;
}
total += nSent;
} while (total < (int)uSize);
return total;
}
int CTCPServer::Send(const Socket ClientSocket, const std::string& strData) const
{
return Send(ClientSocket, strData.c_str(), strData.length());
}
int CTCPServer::Send(const Socket ClientSocket, const std::vector<char>& Data) const
{
return Send(ClientSocket, Data.data(), Data.size());
}
void CTCPServer::Disconnect(Socket& ClientSocket) const
{
if (ClientSocket != INVALID_SOCKET)
{
#if 0//defined(_WIN32)
// The shutdown function disables sends or receives on a socket.
if (shutdown(ClientSocket, SD_RECEIVE) == SOCKET_ERROR)
{
SocketLog("[ERROR]TCPServer, shutdown SD_RECEIVE failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), ClientSocket);
}
#endif
SocketClose(ClientSocket);
}
}