forked from embeddedmz/socket-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPClient.cpp
More file actions
525 lines (426 loc) · 14.1 KB
/
TCPClient.cpp
File metadata and controls
525 lines (426 loc) · 14.1 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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/**
* @file TCPClient.cpp
* @brief implementation of the TCP client class
* @author Mohamed Amine Mzoughi <[email protected]>
*/
#include "TCPClient.h"
namespace
{
std::string SockAddrToString(struct sockaddr *pAddr)
{
if (pAddr == nullptr)
{
return {};
}
static char s[INET6_ADDRSTRLEN > INET_ADDRSTRLEN ? INET6_ADDRSTRLEN : INET_ADDRSTRLEN] = "\0";
std::string strOut;
switch (pAddr->sa_family)
{
case AF_INET: {
struct sockaddr_in *pAddrIn = (struct sockaddr_in *)pAddr;
inet_ntop(AF_INET, &(pAddrIn->sin_addr), s, INET_ADDRSTRLEN);
strOut += s;
strOut += ':';
strOut += std::to_string(ntohs(pAddrIn->sin_port));
break;
}
case AF_INET6: {
struct sockaddr_in6 *pAddrIn6 = (struct sockaddr_in6 *)pAddr;
inet_ntop(AF_INET6, &(pAddrIn6->sin6_addr), s, INET6_ADDRSTRLEN);
strOut += s;
strOut += ':';
strOut += std::to_string(ntohs(pAddrIn6->sin6_port));
break;
}
default:
return {};
}
return strOut;
}
} // namespace
CTCPClient::CTCPClient(const LogFnCallback oLogger, const SettingsFlag eSettings /*= ALL_FLAGS*/)
: ASocket(oLogger, eSettings),
m_eStatus(DISCONNECTED),
m_pResultAddrInfo(nullptr),
m_ConnectSocket(INVALID_SOCKET),
m_Rng(m_RandDevice())
// m_uRetryCount(0),
// m_uRetryPeriod(0)
{}
// Method for setting receive timeout. Can be called after Connect
bool CTCPClient::SetRcvTimeout(unsigned int msec_timeout) {
#ifndef WINDOWS
struct timeval t = ASocket::TimevalFromMsec(msec_timeout);
return this->SetRcvTimeout(t);
#else
int iErr;
// it's expecting an int but it doesn't matter...
iErr = setsockopt(m_ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&msec_timeout, sizeof(struct timeval));
if (iErr < 0) {
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPServer][Error] CTCPClient::SetRcvTimeout : Socket error in SO_RCVTIMEO call to setsockopt.");
return false;
}
return true;
#endif
}
#ifndef WINDOWS
bool CTCPClient::SetRcvTimeout(struct timeval timeout) {
int iErr;
iErr = setsockopt(m_ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (char*) &timeout, sizeof(struct timeval));
if (iErr < 0) {
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPServer][Error] CTCPClient::SetRcvTimeout : Socket error in SO_RCVTIMEO call to setsockopt.");
return false;
}
return true;
}
#endif
// Method for setting send timeout. Can be called after Connect
bool CTCPClient::SetSndTimeout(unsigned int msec_timeout) {
#ifndef WINDOWS
struct timeval t = ASocket::TimevalFromMsec(msec_timeout);
return this->SetSndTimeout(t);
#else
int iErr;
// it's expecting an int but it doesn't matter...
iErr = setsockopt(m_ConnectSocket, SOL_SOCKET, SO_SNDTIMEO, (char*)&msec_timeout, sizeof(struct timeval));
if (iErr < 0) {
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPServer][Error] CTCPClient::SetSndTimeout : Socket error in SO_SNDTIMEO call to setsockopt.");
return false;
}
return true;
#endif
}
#ifndef WINDOWS
bool CTCPClient::SetSndTimeout(struct timeval timeout) {
int iErr;
iErr = setsockopt(m_ConnectSocket, SOL_SOCKET, SO_SNDTIMEO, (char*) &timeout, sizeof(struct timeval));
if (iErr < 0) {
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPServer][Error] CTCPClient::SetSndTimeout : Socket error in SO_SNDTIMEO call to setsockopt.");
return false;
}
return true;
}
#endif
// Connexion au serveur
bool CTCPClient::Connect(const std::string& strServer, const std::string& strPort)
{
if (m_eStatus == CONNECTED)
{
Disconnect();
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPClient][Warning] Opening a new connexion. The last one was automatically closed.");
}
#ifdef WINDOWS
ZeroMemory(&m_HintsAddrInfo, 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;
/* Resolve the server address and port */
int iResult = getaddrinfo(strServer.c_str(), strPort.c_str(), &m_HintsAddrInfo, &m_pResultAddrInfo);
if (iResult != 0)
{
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog(StringFormat("[TCPClient][Error] getaddrinfo failed : %d", iResult));
if (m_pResultAddrInfo != nullptr)
{
freeaddrinfo(m_pResultAddrInfo);
m_pResultAddrInfo = nullptr;
}
return false;
}
// socket creation
m_ConnectSocket = socket(m_pResultAddrInfo->ai_family, // AF_INET
m_pResultAddrInfo->ai_socktype, // SOCK_STREAM
m_pResultAddrInfo->ai_protocol);// IPPROTO_TCP
if (m_ConnectSocket == INVALID_SOCKET)
{
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog(StringFormat("[TCPClient][Error] socket failed : %d", WSAGetLastError()));
freeaddrinfo(m_pResultAddrInfo);
m_pResultAddrInfo = nullptr;
return false;
}
// Fixes windows 0.2 second delay sending (buffering) data.
int on = 1;
int iErr;
iErr = setsockopt(m_ConnectSocket, IPPROTO_TCP, TCP_NODELAY, (char*)&on, sizeof(on));
if (iErr == INVALID_SOCKET)
{
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPClient][Error] Socket error in call to setsockopt");
closesocket(m_ConnectSocket);
freeaddrinfo(m_pResultAddrInfo); m_pResultAddrInfo = nullptr;
return false;
}
/*
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// The sockaddr_in structure specifies the address family,
// IP address, and port of the server to be connected to.
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
clientService.sin_port = htons(27015);
*/
// connexion to the server
//unsigned uRetry = 0;
//do
//{
iResult = connect(m_ConnectSocket,
m_pResultAddrInfo->ai_addr,
static_cast<int>(m_pResultAddrInfo->ai_addrlen));
//iResult = connect(m_ConnectSocket, (SOCKADDR*)&clientService, sizeof(clientService));
//if (iResult != SOCKET_ERROR)
//break;
// retry mechanism
//if (uRetry < m_uRetryCount)
//if (m_eSettingsFlags & ENABLE_LOG)
/*m_oLog(StringFormat("[TCPClient][Error] connect retry %u after %u second(s)",
m_uRetryCount + 1, m_uRetryPeriod));*/
//if (m_uRetryPeriod > 0)
//{
//for (unsigned uSec = 0; uSec < m_uRetryPeriod; uSec++)
//Sleep(1000);
//}
//} while (iResult == SOCKET_ERROR && ++uRetry < m_uRetryCount);
freeaddrinfo(m_pResultAddrInfo);
m_pResultAddrInfo = nullptr;
if (iResult != SOCKET_ERROR)
{
m_eStatus = CONNECTED;
return true;
}
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog(StringFormat("[TCPClient][Error] Unable to connect to server : %d", WSAGetLastError()));
#else
memset(&m_HintsAddrInfo, 0, sizeof m_HintsAddrInfo);
m_HintsAddrInfo.ai_family = AF_INET; // AF_INET or AF_INET6 to force version or use AF_UNSPEC
m_HintsAddrInfo.ai_socktype = SOCK_STREAM;
//m_HintsAddrInfo.ai_flags = 0;
//m_HintsAddrInfo.ai_protocol = 0; /* Any protocol */
int iAddrInfoRet = getaddrinfo(strServer.c_str(), strPort.c_str(), &m_HintsAddrInfo, &m_pResultAddrInfo);
if (iAddrInfoRet != 0)
{
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog(StringFormat("[TCPClient][Error] getaddrinfo failed : %s", gai_strerror(iAddrInfoRet)));
if (m_pResultAddrInfo != nullptr)
{
freeaddrinfo(m_pResultAddrInfo);
m_pResultAddrInfo = nullptr;
}
return false;
}
/* getaddrinfo() returns a list of address structures.
* Try each address until we successfully connect(2).
* If socket(2) (or connect(2)) fails, we (close the socket
* and) try the next address. */
std::ostringstream strAddrList;
size_t uTmpIndex = 0;
size_t uSize = 0;
struct addrinfo *pTmpPtr = m_pResultAddrInfo;
for (pTmpPtr = m_pResultAddrInfo; pTmpPtr != nullptr; pTmpPtr = pTmpPtr->ai_next, ++uTmpIndex)
{
++uSize;
if (uTmpIndex != 0)
{
strAddrList << ", ";
}
strAddrList << StringFormat("[%d] = '%s'", uTmpIndex, SockAddrToString(pTmpPtr->ai_addr).data());
}
std::uniform_int_distribution<size_t> RngGen(0, uSize - 1);
size_t uStartIndex = 0;
if (uSize > 0)
{
uStartIndex = RngGen(m_Rng);
}
if (m_eSettingsFlags & ENABLE_LOG)
{
m_oLog(StringFormat("[TCPClient][Info] Got %d address%s from getaddrinfo, starting from index %d", uSize,
uSize > 1 ? "es" : "", uStartIndex));
m_oLog(StringFormat("[TCPClient][Info] Address list: { %s }", strAddrList.str().data()));
}
struct addrinfo *pResPtr = m_pResultAddrInfo;
for (size_t uIndex = 0; uIndex < uStartIndex; ++uIndex)
{
pResPtr = pResPtr->ai_next;
}
uTmpIndex = uStartIndex;
for (size_t uIndex = 0; uIndex < uSize; ++uIndex, ++uTmpIndex)
{
// create socket
m_ConnectSocket = socket(pResPtr->ai_family, pResPtr->ai_socktype, pResPtr->ai_protocol);
if (m_ConnectSocket >= 0)
{
// connexion to the server
const auto ConnectionTimeBegin = std::chrono::steady_clock::now();
int iConRet = connect(m_ConnectSocket, pResPtr->ai_addr, pResPtr->ai_addrlen);
const auto ConnectionTimeEnd = std::chrono::steady_clock::now();
if (iConRet >= 0) // or != -1
{
/* Success */
m_eStatus = CONNECTED;
m_strLastAddress = SockAddrToString(pResPtr->ai_addr);
if (m_eSettingsFlags & ENABLE_LOG)
{
const auto TimeElapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(ConnectionTimeEnd - ConnectionTimeBegin)
.count();
m_oLog(StringFormat(
"[TCPClient][Info] Successfully connected to address %s at index %d. Connection took %d ms",
m_strLastAddress.data(), uTmpIndex, TimeElapsed));
}
if (m_pResultAddrInfo != nullptr)
{
freeaddrinfo(m_pResultAddrInfo);
m_pResultAddrInfo = nullptr;
}
return true;
}
}
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog(StringFormat("[TCPClient][Info] Connection to address %s at index %d failed",
SockAddrToString(pResPtr->ai_addr).data(), uTmpIndex));
if (pResPtr->ai_next == nullptr)
{
uTmpIndex = 0;
pResPtr = m_pResultAddrInfo;
}
else
{
pResPtr = pResPtr->ai_next;
}
close(m_ConnectSocket);
}
if (m_pResultAddrInfo != nullptr)
{
freeaddrinfo(m_pResultAddrInfo); /* No longer needed */
m_pResultAddrInfo = nullptr;
}
/* No address succeeded */
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPClient][Error] no such host.");
#endif
return false;
}
bool CTCPClient::Send(const char* pData, const size_t uSize) const
{
if (!pData || !uSize)
return false;
if (m_eStatus != CONNECTED)
{
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPClient][Error] send failed : not connected to a server.");
return false;
}
int total = 0;
do
{
const int flags = 0;
int nSent;
nSent = send(m_ConnectSocket, pData + total, uSize - total, flags);
if (nSent < 0)
{
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPClient][Error] Socket error in call to send.");
return false;
}
total += nSent;
} while(total < uSize);
return true;
}
bool CTCPClient::Send(const std::string& strData) const
{
return Send(strData.c_str(), strData.length());
}
bool CTCPClient::Send(const std::vector<char>& Data) const
{
return Send(Data.data(), Data.size());
}
/* ret > 0 : bytes received
* ret == 0 : connection closed
* ret < 0 : recv failed
*/
int CTCPClient::Receive(char* pData, const size_t uSize, bool bReadFully /*= true*/) const
{
if (!pData || !uSize)
return -2;
if (m_eStatus != CONNECTED)
{
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPClient][Error] recv failed : not connected to a server.");
return -1;
}
#ifdef WINDOWS
int tries = 0;
#endif
int total = 0;
do
{
int nRecvd = recv(m_ConnectSocket, pData + total, uSize - total, 0);
if (nRecvd == 0)
{
// peer shut down
break;
}
#ifdef WINDOWS
if ((nRecvd < 0) && (WSAGetLastError() == WSAENOBUFS))
{
// On long messages, Windows recv sometimes fails with WSAENOBUFS, but
// will work if you try again.
if ((tries++ < 1000))
{
Sleep(1);
continue;
}
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog("[TCPClient][Error] Socket error in call to recv.");
break;
}
#endif
total += nRecvd;
} while (bReadFully && (total < uSize));
return total;
}
bool CTCPClient::Disconnect()
{
if (m_eStatus != CONNECTED)
return true;
m_eStatus = DISCONNECTED;
#ifdef WINDOWS
// shutdown the connection since no more data will be sent
int iResult = shutdown(m_ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR)
{
if (m_eSettingsFlags & ENABLE_LOG)
m_oLog(StringFormat("[TCPClient][Error] shutdown failed : %d", WSAGetLastError()));
return false;
}
closesocket(m_ConnectSocket);
if (m_pResultAddrInfo != nullptr)
{
freeaddrinfo(m_pResultAddrInfo);
m_pResultAddrInfo = nullptr;
}
#else
close(m_ConnectSocket);
#endif
m_ConnectSocket = INVALID_SOCKET;
return true;
}
CTCPClient::~CTCPClient()
{
if (m_eStatus == CONNECTED)
Disconnect();
}