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
301 lines (258 loc) · 8.82 KB
/
TCPClient.cpp
File metadata and controls
301 lines (258 loc) · 8.82 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
/**
* @file TCPClient.cpp
* @brief implementation of the TCP client class
* @author Mohamed Amine Mzoughi <[email protected]>
*/
#include "TCPClient.h"
#include <cassert>
CTCPClient::CTCPClient(const LogFnCallback& oLogger, const SettingsFlag eSettings /*= ALL_FLAGS*/)
: ASocket(oLogger, eSettings)
, m_eStatus(DISCONNECTED)
, m_ConnectSocket(INVALID_SOCKET)
//, m_uRetryCount(0)
//, m_uRetryPeriod(0)
, m_pResultAddrInfo(nullptr)
, m_HintsAddrInfo()
{
}
CTCPClient::~CTCPClient()
{
Disconnect();
}
// Method for setting receive timeout. Can be called after Connect
bool CTCPClient::SetRcvTimeout(unsigned int msec_timeout)
{
bool ret_val = ASocket::SetRcvTimeout(m_ConnectSocket, msec_timeout);
if (!ret_val)
{
SocketLog("[ERROR]TCPClient, setsockopt SOL_SOCKET SO_RCVTIMEO failed[%d:%s][%d][%u]", GetSocketError(), strerror(GetSocketError()), m_ConnectSocket, msec_timeout);
}
return ret_val;
}
#ifndef _WIN32
bool CTCPClient::SetRcvTimeout(const struct timeval& timeout)
{
bool ret_val = ASocket::SetRcvTimeout(m_ConnectSocket, timeout);
if (!ret_val)
{
SocketLog("[ERROR]TCPClient, setsockopt SOL_SOCKET SO_RCVTIMEO failed[%d:%s][%d][%u:%u]", GetSocketError(), strerror(GetSocketError()), m_ConnectSocket, timeout.tv_sec, timeout.tv_usec);
}
return ret_val;
}
#endif
// Method for setting send timeout. Can be called after Connect
bool CTCPClient::SetSndTimeout(unsigned int msec_timeout)
{
bool ret_val = ASocket::SetSndTimeout(m_ConnectSocket, msec_timeout);
if (!ret_val)
{
SocketLog("[ERROR]TCPClient, setsockopt SOL_SOCKET SO_SNDTIMEO failed[%d:%s][%d][%u]", GetSocketError(), strerror(GetSocketError()), m_ConnectSocket, msec_timeout);
}
return ret_val;
}
#ifndef _WIN32
bool CTCPClient::SetSndTimeout(const struct timeval& timeout)
{
bool ret_val = ASocket::SetSndTimeout(m_ConnectSocket, timeout);
if (!ret_val)
{
SocketLog("[ERROR]TCPClient, setsockopt SOL_SOCKET SO_SNDTIMEO failed[%d:%s][%d][%u:%u]", GetSocketError(), strerror(GetSocketError()), m_ConnectSocket, timeout.tv_sec, timeout.tv_usec);
}
return ret_val;
}
#endif
// Connexion au serveur
bool CTCPClient::Connect(const std::string& strServer, const std::string& strPort)
{
if (m_eStatus == CONNECTED)
{
Disconnect();
SocketLog("[WARN ]TCPClient, opening a new connexion. the last one was automatically closed[%s:%s]", strServer.c_str(), strPort.c_str());
}
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;
/* Resolve the server address and port */
int iResult = getaddrinfo(strServer.c_str(), strPort.c_str(), &m_HintsAddrInfo, &m_pResultAddrInfo);
if (iResult != 0)
{
SocketLog("[ERROR]TCPClient, getaddrinfo failed[%d:%s][%s:%s]", iResult, GaiStrerror(iResult), strServer.c_str(), strPort.c_str());
return false;
}
bool isOK = 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. */
for (struct addrinfo* pResPtr = m_pResultAddrInfo; pResPtr != nullptr; pResPtr = pResPtr->ai_next)
{
// create socket
m_ConnectSocket = socket(pResPtr->ai_family, pResPtr->ai_socktype, pResPtr->ai_protocol);
if (m_ConnectSocket == INVALID_SOCKET)
{
SocketLog("[WARN ]TCPClient, create socket failed[%d:%s]", GetSocketError(), strerror(GetSocketError()));
continue;
}
// Fixes windows 0.2 second delay sending (buffering) data.
int on = 1;
if (setsockopt(m_ConnectSocket, IPPROTO_TCP, TCP_NODELAY, (char*)&on, sizeof(on)) == SOCKET_ERROR)
{
SocketLog("[WARN ]TCPClient, setsockopt IPPROTO_TCP TCP_NODELAY failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), m_ConnectSocket);
}
// connexion to the server
if (connect(m_ConnectSocket, pResPtr->ai_addr, static_cast<int>(pResPtr->ai_addrlen)) == SOCKET_ERROR)
{
int iErrCode = GetSocketError();
if (!SOCKET_ERR_CONNECT_RETRIABLE(iErrCode))
{
SocketLog("[WARN ]TCPClient, connect failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), m_ConnectSocket);
assert(m_ConnectSocket != INVALID_SOCKET);
SocketClose(m_ConnectSocket);
continue;
}
}
isOK = true;
m_eStatus = CONNECTED;
SocketLog("[INFO ]TCPClient, connected[%d]", m_ConnectSocket);
break;
}
if (m_pResultAddrInfo != nullptr)
{
freeaddrinfo(m_pResultAddrInfo); /* No longer needed */
m_pResultAddrInfo = nullptr;
}
/* No address succeeded */
if (!isOK)
{
SocketLog("[ERROR]TCPClient, Connect failed[%s:%s]", strServer.c_str(), strPort.c_str());
}
return isOK;
}
/* ret > 0 : bytes received
* ret == 0 : connection closed
* ret < 0 : recv failed
*/
int CTCPClient::Receive(char* pData, size_t uSize, bool bReadFully /*= true*/) const
{
if (m_eStatus != CONNECTED || m_ConnectSocket == INVALID_SOCKET)
{
SocketLog("[ERROR]TCPClient, recv failed[not connected to a server.]");
return -1;
}
if (pData == nullptr && uSize != 0)
{
SocketLog("[ERROR]TCPClient, recv failed[%d][%p:%zu]", m_ConnectSocket, pData, uSize);
return -2;
}
#if 0
#ifdef _WIN32
int tries = 0;
#endif
#endif
int total = 0;
do
{
int nRecvd = recv(m_ConnectSocket, 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]TCPClient, recv failed[%d:%s][%d]", iErrCode, strerror(iErrCode), m_ConnectSocket);
return -1;
}
break;
}
if (nRecvd == 0)
{
if (total == 0)
{
SocketLog("[INFO ]TCPClient, peer shut down[%d]", m_ConnectSocket);
return 0;
}
break;
}
total += nRecvd;
} while (bReadFully && (total < (int)uSize));
return total;
}
int CTCPClient::Send(const char* pData, size_t uSize) const
{
if (m_eStatus != CONNECTED || m_ConnectSocket == INVALID_SOCKET)
{
SocketLog("[ERROR]TCPClient, send failed[not connected to a server.]");
return -1;
}
if (pData == nullptr && uSize != 0)
{
SocketLog("[WARN ]TCPClient, send failed[%d][%p:%zu]", m_ConnectSocket, pData, uSize);
return -1;
}
int total = 0;
do
{
int nSent = send(m_ConnectSocket, 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 ]TCPClient, send shutdowned SHUT_WR[%d:%s][%d]", iErrCode, strerror(iErrCode), m_ConnectSocket);
break;
}
SocketLog("[ERROR]TCPClient, send failed[%d:%s][%d]", iErrCode, strerror(iErrCode), m_ConnectSocket);
return -1;
}
total += nSent;
} while (total < (int)uSize);
return total;
}
int CTCPClient::Send(const std::string& strData) const
{
return Send(strData.c_str(), strData.length());
}
int CTCPClient::Send(const std::vector<char>& Data) const
{
return Send(Data.data(), Data.size());
}
void CTCPClient::Disconnect()
{
if (m_eStatus != CONNECTED)
{
m_eStatus = DISCONNECTED;
}
if (m_ConnectSocket != INVALID_SOCKET)
{
#if 0//defined(_WIN32)
// shutdown the connection since no more data will be sent
if (shutdown(m_ConnectSocket, SD_SEND) == SOCKET_ERROR)
{
SocketLog("[ERROR]TCPClient, shutdown SD_SEND failed[%d:%s][%d]", GetSocketError(), strerror(GetSocketError()), m_ConnectSocket);
}
#endif
SocketClose(m_ConnectSocket);
}
}