-
Notifications
You must be signed in to change notification settings - Fork 9
/
TCPSocket.cpp
618 lines (522 loc) · 15.3 KB
/
TCPSocket.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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// Remote Desktop System - remote controlling of multiple PC's
// Copyright (C) 2000-2009 GravyLabs LLC
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
// TCPSocket.cpp : implementation file
// Implementation of AsyncSocket derived class.
// This class only works with versions of windows that recognize the TransmitPackets API function call
//
#include "stdafx.h"
#include "TCPSocket.h"
#include "Packet.h"
CTCPSocket::CTCPSocket() : baseclass(),
m_bListening(FALSE),m_hWndParent(NULL),TransmitPackets(NULL)
{
}
CTCPSocket::~CTCPSocket()
{
}
// Initialize the transmit packet function pointer
BOOL CTCPSocket::InitTP()
{
// Create the transmit packet function pointer
DWORD len;
static const GUID guid = WSAID_TRANSMITPACKETS;
if (WSAIoctl(m_hSocket,SIO_GET_EXTENSION_FUNCTION_POINTER,(void*)&guid,sizeof(guid),&TransmitPackets,sizeof(TransmitPackets),&len,NULL,NULL))
return FALSE;
return TRUE;
}
// Create a new socket
BOOL CTCPSocket::Create(int nSocketPort)
{
BOOL bCreate = FALSE;
if (nSocketPort == 0)
{
// Create the outbound connection
bCreate = baseclass::Create();
// Receive notifications for connections, reading data, and disconnections
AsyncSelect(FD_CONNECT | FD_READ | FD_CLOSE);
}
else
{
// Create the listener socket
bCreate = baseclass::Create(nSocketPort);
// Receive notifications of a waiting connection, reading data, and disconnections
AsyncSelect(FD_ACCEPT | FD_READ | FD_CLOSE);
// Start listening
if (bCreate)
m_bListening = baseclass::Listen(SOMAXCONN);
}
// Create the transmit packet function pointer
if (!InitTP())
bCreate = FALSE;
return bCreate;
}
// Set the parent window handle for events to be posted back to the parent with WM_APP messags
void CTCPSocket::SetParent(HWND hWndParent)
{
m_hWndParent = hWndParent;
}
// Make a connection using a outbound socket
BOOL CTCPSocket::Connect(LPCTSTR lpszHostAddress,UINT nHostPort)
{
if (!m_bListening)
return baseclass::Connect(lpszHostAddress,nHostPort);
return FALSE;
}
// Shutdown the socket
BOOL CTCPSocket::ShutDown(int nHow)
{
return baseclass::ShutDown(nHow);
}
// Notification of a pending inbound connection
void CTCPSocket::OnAccept(int nErrorCode)
{
ASSERT(m_bListening == TRUE);
baseclass::OnAccept(nErrorCode);
// Send the custom WM_ACCEPTCONN message
if (m_hWndParent != NULL)
{
// Send and wait for processing
SendMessage(m_hWndParent,WM_ACCEPTCONN,(WPARAM)this,0);
}
}
// Notification that the connection has been successfully made
void CTCPSocket::OnConnect(int nErrorCode)
{
baseclass::OnConnect(nErrorCode);
// Send the custom WM_MAKECONN message
if (m_hWndParent != NULL)
{
// Send and wait for processing
SendMessage(m_hWndParent,WM_MAKECONN,(WPARAM)this,(LPARAM)nErrorCode);
}
}
// Notification of readiness to receive data
void CTCPSocket::OnReceive(int nErrorCode)
{
ASSERT(m_bListening == FALSE);
baseclass::OnReceive(nErrorCode);
// Send the custom WM_RECEIVEDATA message
if (m_hWndParent != NULL)
{
// Send and wait for processing
SendMessage(m_hWndParent,WM_RECEIVEDATA,(WPARAM)this,0);
}
}
// Notification that the connection has been closed
void CTCPSocket::OnClose(int nErrorCode)
{
baseclass::OnClose(nErrorCode);
// Shutdown and close the socket
ShutDown();
Close();
// Send the custom WM_CLOSECONN message
if (m_hWndParent != NULL)
{
// Send and wait for processing
SendMessage(m_hWndParent,WM_CLOSECONN,(WPARAM)this,0);
}
}
// Helper for sorting, since order really doesn't matter, use the memory address
bool CTCPSocket::operator < (const CTCPSocket & rhs)
{
return (DWORD_PTR)this < (DWORD_PTR)(&rhs);
}
// Helper to send a packet of data
CTCPSocket & CTCPSocket::operator << (CPacket & rhs)
{
// Enable blocking mode and prevent events
DWORD dwArgument = 0;
AsyncSelect(dwArgument);
IOCtl(FIONBIO,&dwArgument);
// Send the packet
rhs.SerializePacket(this,true);
// Disable blocking mode and reinstate events
dwArgument = FD_CONNECT | FD_READ | FD_CLOSE;
IOCtl(FIONBIO,&dwArgument);
AsyncSelect(dwArgument);
// Return a reference to "this" class for chaining
return *this;
}
// Helper to receive a packet
CTCPSocket & CTCPSocket::operator >> (CPacket & rhs)
{
// Enable blocking mode and prevent events
DWORD dwArgument = 0;
AsyncSelect(dwArgument);
IOCtl(FIONBIO,&dwArgument);
// Receive the packet
rhs.SerializePacket(this,false);
// Disable blocking mode and reinstate events
dwArgument = FD_CONNECT | FD_READ | FD_CLOSE;
IOCtl(FIONBIO,&dwArgument);
AsyncSelect(dwArgument);
// Return a reference to "this" class for chaining
return *this;
}
// Send the buffer of data
int CTCPSocket::Send(const void * lpBuf,int nBufLen,int nFlags)
{
// Test for a function pointer to the TransmitPackets function
if (!TransmitPackets)
return 0;
// Create the transmit buffer data structure
_TRANSMIT_PACKETS_ELEMENT TPE;
TPE.dwElFlags = TP_ELEMENT_MEMORY;
TPE.cLength = nBufLen;
TPE.pBuffer = (PVOID)lpBuf;
// Transmit the packet
BOOL bTransmit = TransmitPackets(m_hSocket,&TPE,1,nBufLen,NULL,TF_USE_KERNEL_APC);
return nBufLen;
}
// Receive the buffer of data
int CTCPSocket::Receive(void * lpBuf,int nBufLen,int nFlags)
{
int nTotalRecv = 0,nRecvAttempt = 0;
while (nTotalRecv < nBufLen)
{
int nRecv = baseclass::Receive((LPSTR)lpBuf + nTotalRecv,nBufLen - nTotalRecv,nFlags);
if (nRecv == SOCKET_ERROR)
return nRecv;
nTotalRecv += nRecv;
// Test for a dropped connection during a receive
if (nRecv == 0)
{
nRecvAttempt++;
Sleep(300);
}
if (nRecvAttempt == 10)
return 0;
}
return nTotalRecv;
}
/////////////////////////////////////////////////////////////////////////////////
// Handle the socket notifications as well as the basic initialization
BEGIN_MESSAGE_MAP(CSocketWndSink,CWnd)
ON_WM_CREATE()
ON_WM_PAINT()
ON_MESSAGE(WM_MAKECONN, &CSocketWndSink::OnMakeConn)
ON_MESSAGE(WM_RECEIVEDATA, &CSocketWndSink::OnReceiveData)
ON_MESSAGE(WM_CLOSECONN, &CSocketWndSink::OnCloseConn)
END_MESSAGE_MAP()
// Constructor
CSocketWndSink::CSocketWndSink(HWND hWndParent) : CWnd(), m_hWndParent(hWndParent), m_bConnected(FALSE)
{
// Create the window
if (!CreateEx(0,AfxRegisterWndClass(0),_T("RDVSink"),WS_OVERLAPPED,0,0,0,0,NULL,NULL))
DebugMsg(_T("%s\n"), TEXT("Failed to create a RDV window notification sink"));
}
// Destructor
CSocketWndSink::~CSocketWndSink()
{
if (m_bConnected)
ShutDown();
}
// Create the window
int CSocketWndSink::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
MoveWindow(0,0,0,0);
return 0;
}
// Paint the window
void CSocketWndSink::OnPaint()
{
CPaintDC dc(this);
}
// Return the connected status
BOOL CSocketWndSink::IsConnected()
{
return m_bConnected;
}
// Shutdown and close the connection
void CSocketWndSink::ShutDown()
{
m_Socket.ShutDown();
m_Socket.Close();
m_bConnected = FALSE;
}
// Connection has been made
LRESULT CSocketWndSink::OnMakeConn(WPARAM wParam,LPARAM lParam)
{
int nErrorCode = (int)lParam;
if (nErrorCode)
{
// Get the error message
CString csErrorMsg;
switch( nErrorCode )
{
case WSAEADDRINUSE:
{
csErrorMsg = "The specified address is in use.\n";
break;
}
case WSAEADDRNOTAVAIL:
{
csErrorMsg = "The specified address is not available from the local machine.\n";
break;
}
case WSAEAFNOSUPPORT:
{
csErrorMsg = "Addresses in the specified family cannot be used with this socket.\n";
break;
}
case WSAEDESTADDRREQ:
{
csErrorMsg = "A destination address is required.\n";
break;
}
case WSAEFAULT:
{
csErrorMsg = "The lpSockAddrLen argument is incorrect.\n";
break;
}
case WSAEINVAL:
{
csErrorMsg = "The socket is already bound to an address.\n";
break;
}
case WSAEISCONN:
{
csErrorMsg = "The socket is already connected.\n";
break;
}
case WSAEMFILE:
{
csErrorMsg = "No more file descriptors are available.\n";
break;
}
case WSAENETUNREACH:
{
csErrorMsg = "The network cannot be reached from this host at this time.\n";
break;
}
case WSAENOBUFS:
{
csErrorMsg = "No buffer space is available. The socket cannot be connected.\n";
break;
}
case WSAENOTCONN:
{
csErrorMsg = "The socket is not connected.\n";
break;
}
case WSAENOTSOCK:
{
csErrorMsg = "The descriptor is a file, not a socket.\n";
break;
}
case WSAETIMEDOUT:
{
csErrorMsg = "The attempt to connect timed out without establishing a connection. \n";
break;
}
case WSAECONNREFUSED:
default:
{
csErrorMsg = "The attempt to connect was forcefully rejected.\n";
break;
}
}
// Notify
AfxMessageBox(csErrorMsg);
}
else
{
// Set the connected state and connection event
m_bConnected = TRUE;
#if defined(_DEBUG)
DebugMsg(_T("Connected to the server on thread %d\n"), GetCurrentThreadId());
#endif
}
return lParam;
}
// Received data event from the desktop server, now read the data
LRESULT CSocketWndSink::OnReceiveData(WPARAM wParam,LPARAM lParam)
{
// Receive the data
CPacket Packet;
// Receive the image
m_Socket >> Packet;
// Send the packet and wait for it to be processed
::SendMessage(m_hWndParent,WM_RECEIVEDATA,(WPARAM)this,(LPARAM)&Packet);
return 1;
}
// Connection telling us that a connection has been closed
LRESULT CSocketWndSink::OnCloseConn(WPARAM wParam,LPARAM lParam)
{
return 1;
}
// Make a connection to the server
void CSocketWndSink::Connect(CString csIp,CString csPort)
{
// Create the connection oriented socket
m_Socket.Create();
// Set the parent for receiving socket notifications
m_Socket.SetParent(GetSafeHwnd());
// Attempt to connect to the server
m_Socket.Connect(csIp, _ttoi(csPort));
}
/////////////////////////////////////////////////////////////////////////////////
IMPLEMENT_DYNCREATE(CSocketWndSinkThread, CWinThread)
CSocketWndSinkThread::CSocketWndSinkThread() throw(...)
{
throw;
}
// Take the update rectangle
CSocketWndSinkThread::CSocketWndSinkThread(HANDLE * phWork,HWND hWndParent,CString csIp,CString csPort) :
m_phWork(phWork), m_hWndParent(hWndParent), m_csIp(csIp), m_csPort(csPort), m_pSocketWnd(NULL), m_bPumpMessage(false)
{
// Create the initialization signaling event
m_hPumpMessage = CreateEvent(NULL,FALSE,FALSE,NULL);
// Create the work signaling event
HANDLE & hWork = *m_phWork;
hWork = CreateEvent(NULL,FALSE,FALSE,NULL);
// Initialize the event
SetEvent(hWork);
// Create the thread
CreateThread();
SetThreadPriority(THREAD_PRIORITY_TIME_CRITICAL);
// Wait for the thread to initialize and signal its message pump has started
WaitForSingleObject(m_hPumpMessage,INFINITE);
// Close the initialization event
CloseHandle(m_hPumpMessage);
m_hPumpMessage = NULL;
}
CSocketWndSinkThread::~CSocketWndSinkThread()
{
// Close the work signaling event
HANDLE & hWork = *m_phWork;
CloseHandle(hWork);
}
BOOL CSocketWndSinkThread::InitInstance()
{
// Initialize sockets for each thread
if (!AfxSocketInit())
return FALSE;
// Create the window for socket event notifications
m_pSocketWnd = new CSocketWndSink(m_hWndParent);
ASSERT(m_pSocketWnd != NULL);
#if defined(_DEBUG)
DebugMsg(_T("Thread %d ready\n"), GetCurrentThreadId());
#endif
return TRUE;
}
int CSocketWndSinkThread::ExitInstance()
{
// Delete the socket window event notification window
if (m_pSocketWnd)
{
// Shutdown the connection if it is still open
if (m_pSocketWnd->IsConnected())
m_pSocketWnd->ShutDown();
// Destroy the window
m_pSocketWnd->DestroyWindow();
// Delete the object
delete m_pSocketWnd;
m_pSocketWnd = NULL;
}
// Base class handles normal exit sequence
return CWinThread::ExitInstance();
}
// Use the message pump as a marker to indicate the thread can accept posted messages
BOOL CSocketWndSinkThread::PumpMessage()
{
// Test for initialization
if (!m_bPumpMessage)
{
// The message pump is active
m_bPumpMessage = true;
// Signal completion of this stage
SetEvent(m_hPumpMessage);
}
// Allow the base class to handle the message pump
return CWinThread::PumpMessage();
}
// Return the connected status
BOOL CSocketWndSinkThread::IsConnected()
{
return m_pSocketWnd && m_pSocketWnd->IsConnected();
}
// These functions are called by PostThreadMessage
BEGIN_MESSAGE_MAP(CSocketWndSinkThread, CWinThread)
ON_THREAD_MESSAGE(WM_CONNECTSERVER, &CSocketWndSinkThread::OnConnectServer)
ON_THREAD_MESSAGE(WM_ENDTHREAD, &CSocketWndSinkThread::OnEndThread)
END_MESSAGE_MAP()
// Connect to the server
void CSocketWndSinkThread::OnConnectServer(WPARAM wParam,LPARAM lParam)
{
// Create the connection event
if (m_pSocketWnd)
m_pSocketWnd->Connect(m_csIp,m_csPort);
}
void CSocketWndSinkThread::OnEndThread(WPARAM wParam,LPARAM lParam)
{
// Shutdown and close the connection
if (IsConnected())
m_pSocketWnd->ShutDown();
// End the thread
PostQuitMessage(0);
}
//////////////////////////////////////////////////////////////////////////////////
// Handle the socket notifications as well as the basic initialization
BEGIN_MESSAGE_MAP(CSocketEvent,CWnd)
ON_WM_CREATE()
ON_WM_PAINT()
ON_MESSAGE(WM_RECEIVEDATA, &CSocketEvent::OnReceiveData)
ON_MESSAGE(WM_CLOSECONN, &CSocketEvent::OnCloseConn)
END_MESSAGE_MAP()
// Constructor
CSocketEvent::CSocketEvent(CWinThread * pThread) : CWnd(), m_pThread(pThread), m_bClosed(FALSE)
{
// Create the window
if (!CreateEx(0,AfxRegisterWndClass(0),_T("RDSSink"),WS_OVERLAPPED,0,0,0,0,NULL,NULL))
DebugMsg(_T("%s\n"), TEXT("Failed to create a RDS window notification sink"));
}
// Destructor
CSocketEvent::~CSocketEvent()
{
}
// Return the closed status of the socket
BOOL CSocketEvent::IsClosed()
{
// A valid socket pointer means it received the closed event notification
return m_bClosed;
}
// Create the window
int CSocketEvent::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CWnd::OnCreate(lpCreateStruct) == -1)
return -1;
MoveWindow(0,0,0,0);
return 0;
}
// Paint the window
void CSocketEvent::OnPaint()
{
CPaintDC dc(this);
}
// The socket has data to be read
LRESULT CSocketEvent::OnReceiveData(WPARAM wParam,LPARAM lParam)
{
return 1;
}
// The socket has been closed
LRESULT CSocketEvent::OnCloseConn(WPARAM wParam,LPARAM lParam)
{
// Update the closed status
m_bClosed = TRUE;
// Notify the parent
m_pThread->PostThreadMessage(WM_CLOSECONN,wParam,lParam);
return 1;
}