-
Notifications
You must be signed in to change notification settings - Fork 4
/
CClientSocket.cpp
371 lines (300 loc) · 8.58 KB
/
CClientSocket.cpp
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
/*
Copyright [2010] [Richard Bross]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Client socket
//
// Created: Richard A. Bross
//
// Implements a client connection. You should derive a class from this class
// which implements a ProcessData method for incoming data and also some
// external method for sending data (internally, you can use the SendDataOut
// method).
//
#include "XPlat.h"
#include "CXPlatThread.h"
#include "CBaseSocket.h"
#include "CConnectionSocket.h"
#include "CClientSocket.h"
// constructor
CClientSocket::CClientSocket() : CConnectionSocket(NULL)
{
tStarted = time(NULL);
memset(&hClientThread, 0, sizeof(hClientThread));
bDestroying = bReuse = FALSE;
iLinger = -1;
iConnectError = 0;
bTcpNoDelay = false;
}
CClientSocket::~CClientSocket()
{
bDestroying = TRUE;
// Release connect thread handle
if (sSocket && sSocket != SOCKET_ERROR)
CloseSocket();
if (hClientThread)
{
cCritSection.Lock();
#if defined(_WIN32)
::WaitForSingleObject(hClientThread, INFINITE);
::CloseHandle(hClientThread); // _beginthreadex doesn't auto close the handle
#else
::pthread_join(hClientThread, NULL);
#endif
memset(&hClientThread, 0, sizeof(hClientThread));
cCritSection.Unlock();
};
}
// Set socket options - must be called BEFORE ConnectToServer
void CClientSocket::SetOptions(bool bReuse, int iLinger, bool bTcpNoDelay)
{
this->bReuse = bReuse;
this->iLinger = iLinger;
this->bTcpNoDelay = bTcpNoDelay;
}
// Distribute to either the TCP or UNIX connection code
BOOL CClientSocket::ConnectDispatcher(DWORD dwTimeout)
{
// Use a thread to attempt connection
if (!InitiateConnection())
{
cCritSection.Unlock();
// Close the unused socket
UnprotectedCloseSocket();
return(FALSE);
};
// Wait for the thread to complete
#if defined(_WIN32)
if (::WaitForSingleObject(hClientThread, dwTimeout) == XPLAT_TIMEOUT)
#else
// An event is used instead of pthread_join on Linux so we can timeout
if (cConnectThreadDoneEvent.Lock(dwTimeout) == XPLAT_TIMEOUT)
#endif
{ // Timed out
CloseSocket();
#if defined(_WIN32)
::WaitForSingleObject(hClientThread, INFINITE);
::CloseHandle(hClientThread);
#else // *nix
if (hClientThread)
{
#if defined(__linux) // Linux
// linux sometimes hangs on the __connect() when the socket is closed from another thread!
::pthread_cancel(hClientThread);
#endif
::pthread_join(hClientThread, NULL);
#endif
}
memset(&hClientThread, 0, sizeof(hClientThread));
cCritSection.Unlock();
// Close the unused socket
UnprotectedCloseSocket();
return(FALSE);
};
#if !defined(_WIN32)
if (hClientThread)
::pthread_join(hClientThread, NULL); // Must do this to clean up the thread
#endif
// Release connect thread handle
if (hClientThread)
{
#if defined(_WIN32)
::CloseHandle(hClientThread);
#endif
memset(&hClientThread, 0, sizeof(hClientThread));
};
// Successful?
if (!LastConnectAttemptSuccessful())
{
cCritSection.Unlock();
// Close the unused socket
UnprotectedCloseSocket();
return(FALSE);
};
if (IsConnected())
{
cCritSection.Unlock();
// Close the unused socket
UnprotectedCloseSocket();
return(FALSE);
};
cCritSection.Unlock();
// Start the socket servicing the client
ServiceConnection(sSocket);
return(TRUE);
}
// Connect to a Unix domain socket server
BOOL CClientSocket::ConnectToUnixServer(const char *szUnixPath, DWORD dwTimeout)
{
bConnectAttempt = FALSE;
cCritSection.Lock();
if (bDestroying)
{
cCritSection.Unlock();
return(FALSE);
};
// Already connected?
if (IsConnected())
{
cCritSection.Unlock();
TerminateConnection();
};
// Create the socket
if (!Create(AF_UNIX, SOCK_STREAM, 0, 0, szUnixPath, FALSE, FALSE))
{
::printf("Unable to create the Unix socket: %s\n", szUnixPath);
cCritSection.Unlock();
return(FALSE);
}
// Set up Unix socket address
::memset(&sAddr, 0, sizeof(sAddr));
::memset(&sUAddr, 0, sizeof(sUAddr));
sUAddr.sun_family = AF_UNIX;
::strcpy(sUAddr.sun_path, szUnixPath);
return(ConnectDispatcher(dwTimeout));
}
// Connect to a TCP server
BOOL CClientSocket::ConnectToServer(LPCSTR lpszHostAddress, UINT nHostPort, DWORD dwTimeout)
{
struct hostent *lphost;
bConnectAttempt = FALSE;
cCritSection.Lock();
if (bDestroying)
{
cCritSection.Unlock();
return(FALSE);
};
// Already connected?
if (IsConnected())
{
cCritSection.Unlock();
TerminateConnection();
};
// Make sure we have a host address
if (!lpszHostAddress)
{
cCritSection.Unlock();
return(FALSE);
};
// Create our socket without a "bind". ::connect will establish the port.
Create(AF_INET, SOCK_STREAM, 0, 0, NULL, bReuse, FALSE, iLinger, bTcpNoDelay);
// Set up socket structure
::memset(&sAddr, 0, sizeof(sAddr));
::memset(&sUAddr, 0, sizeof(sUAddr));
sAddr.sin_family = AF_INET;
sAddr.sin_addr.s_addr = inet_addr(lpszHostAddress);
// Name instead of IP address?
if (sAddr.sin_addr.s_addr == INADDR_NONE)
{
PROTECT_CALL
lphost = ::gethostbyname(lpszHostAddress);
if (lphost != NULL)
{
sAddr.sin_addr.s_addr = ((struct in_addr *) lphost->h_addr)->s_addr;
UNPROTECT_CALL
}
else
{
UNPROTECT_CALL
cCritSection.Unlock();
// Close the unused socket
UnprotectedCloseSocket();
return(FALSE);
};
}
// Load port
sAddr.sin_port = htons((u_short) nHostPort);
return(ConnectDispatcher(dwTimeout));
};
// Return the time the server was started
time_t CClientSocket::GetTimeStarted()
{
return(tStarted);
};
// Listen for someone trying to connect
BOOL CClientSocket::InitiateConnection()
{
// Already connected?
if (hClientThread)
{
if (CXPlatThread::IsThreadActive(hClientThread))
return(TRUE);
else
{
#if defined(_WIN32)
::CloseHandle(hClientThread);
#endif
memset(&hClientThread, 0, sizeof(hClientThread));
};
};
#if defined(_WIN32)
unsigned uThread;
hClientThread = (HANDLE) ::_beginthreadex(NULL,
0,
ConnectThread,
(void *) this,
0, // initflag = 0, start suspended
&uThread);
if (hClientThread)
{
::ResumeThread(hClientThread);
return(TRUE);
};
#else
int iReturn;
iReturn = ::pthread_create(&hClientThread, pthread_attr_default, (START_ROUTINE) ConnectThread, (void *) this);
#endif
return(TRUE);
}
// Thread to accept connections
unsigned CClientSocket::ConnectThread(void* pVoid)
{
unsigned uReturn;
CClientSocket *pCSocket = (CClientSocket *) pVoid;
pCSocket->bConnectAttempt = pCSocket->AttemptConnection();
uReturn = pCSocket->bConnectAttempt;
#if !defined(_WIN32)
pCSocket->cConnectThreadDoneEvent.SetEvent();
#endif
return(uReturn);
};
// Thread to accept connections
BOOL CClientSocket::AttemptConnection()
{
int iReturn;
// Thread to connect
try
{ // TCP or Unix
if (sAddr.sin_port != 0)
iReturn = ::connect(sSocket, (struct sockaddr *) &sAddr, sizeof(sAddr));
else
iReturn = ::connect(sSocket, (struct sockaddr *) &sUAddr, strlen(sUAddr.sun_path) + sizeof(sUAddr.sun_family));
}
catch(...)
{
iReturn = SOCKET_ERROR;
}
if (iReturn == SOCKET_ERROR)
iConnectError = XPLAT_WSAGETLASTERR;
else
iConnectError = 0;
return(iReturn != SOCKET_ERROR);
};
// Connect attempt successful?
BOOL CClientSocket::LastConnectAttemptSuccessful()
{
return(bConnectAttempt);
};
// Return the last connection error
int CClientSocket::GetConnectionError()
{
return(iConnectError);
};