This repository has been archived by the owner on Jan 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSocketComm.cpp
1019 lines (878 loc) · 27.5 KB
/
SocketComm.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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///////////////////////////////////////////////////////////////////////////////
// File: SocketComm.cpp
// Version: 1.3
//
// Author: Ernest Laurentin
// E-mail: [email protected]
//
// Implementation of the CSocketComm and associated classes.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this c++ class may cause.
//
// Version history
//
// 1.0 - Initial release.
// 1.1 - Add support for Smart Addressing mode
// 1.2 - Fix various issues with address list (in UDP mode)
// 1.3 - Fix bug when sending message to broadcast address
///////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <stdio.h>
#include <tchar.h>
#include <process.h>
#include <crtdbg.h>
#include "SocketComm.h"
const DWORD DEFAULT_TIMEOUT = 100L;
struct stMessageProxy
{
SockAddrIn address;
BYTE data[BUFFER_SIZE];
};
///////////////////////////////////////////////////////////////////////////////
// SockAddrIn Struct
///////////////////////////////////////////////////////////////////////////////
// Copy
SockAddrIn& SockAddrIn::Copy(const SockAddrIn& sin)
{
memcpy(this, &sin, Size());
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// IsEqual
bool SockAddrIn::IsEqual(const SockAddrIn& sin)
{
// Is it Equal? - ignore 'sin_zero'
return (memcmp(this, &sin, Size()-sizeof(sin_zero)) == 0);
}
///////////////////////////////////////////////////////////////////////////////
// IsGreater
bool SockAddrIn::IsGreater(const SockAddrIn& sin)
{
// Is it Greater? - ignore 'sin_zero'
return (memcmp(this, &sin, Size()-sizeof(sin_zero)) > 0);
}
///////////////////////////////////////////////////////////////////////////////
// IsLower
bool SockAddrIn::IsLower(const SockAddrIn& sin)
{
// Is it Lower? - ignore 'sin_zero'
return (memcmp(this, &sin, Size()-sizeof(sin_zero)) < 0);
}
///////////////////////////////////////////////////////////////////////////////
// CreateFrom
bool SockAddrIn::CreateFrom(LPCTSTR sAddr, LPCTSTR sService, int nFamily /*=AF_INET*/)
{
Clear();
sin_addr.s_addr = htonl( CSocketComm::GetIPAddress(sAddr) );
sin_port = htons( CSocketComm::GetPortNumber( sService ) );
sin_family = nFamily;
return !IsNull();
}
///////////////////////////////////////////////////////////////////////////////
// Construct & Destruct
CSocketComm::CSocketComm() :
m_bServer(false), m_bSmartAddressing(false), m_bBroadcast(false),
m_hComm(INVALID_HANDLE_VALUE), m_hThread(NULL), m_hMutex(NULL)
{
}
CSocketComm::~CSocketComm()
{
StopComm();
}
///////////////////////////////////////////////////////////////////////////////
// Members
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// IsOpen
bool CSocketComm::IsOpen() const
{
return ( INVALID_HANDLE_VALUE != m_hComm );
}
///////////////////////////////////////////////////////////////////////////////
// IsStart
bool CSocketComm::IsStart() const
{
return ( NULL != m_hThread );
}
///////////////////////////////////////////////////////////////////////////////
// IsServer
bool CSocketComm::IsServer() const
{
return m_bServer;
}
///////////////////////////////////////////////////////////////////////////////
// IsBroadcast
bool CSocketComm::IsBroadcast() const
{
return m_bBroadcast;
}
///////////////////////////////////////////////////////////////////////////////
// IsSmartAddressing
bool CSocketComm::IsSmartAddressing() const
{
return m_bSmartAddressing;
}
///////////////////////////////////////////////////////////////////////////////
// GetSocket
SOCKET CSocketComm::GetSocket() const
{
return (SOCKET) m_hComm;
}
///////////////////////////////////////////////////////////////////////////////
// LockList
void CSocketComm::LockList()
{
if (NULL != m_hMutex)
WaitForSingleObject(m_hMutex, INFINITE);
}
///////////////////////////////////////////////////////////////////////////////
// UnlockList
void CSocketComm::UnlockList()
{
if (NULL != m_hMutex)
ReleaseMutex(m_hMutex);
}
///////////////////////////////////////////////////////////////////////////////
// AddToList
void CSocketComm::AddToList(const SockAddrIn& saddr_in)
{
LockList();
m_AddrList.insert( m_AddrList.end(), saddr_in );
UnlockList();
}
///////////////////////////////////////////////////////////////////////////////
// RemoveFromList
void CSocketComm::RemoveFromList(const SockAddrIn& saddr_in)
{
LockList();
m_AddrList.remove( saddr_in );
UnlockList();
}
///////////////////////////////////////////////////////////////////////////////
// SetServerState
void CSocketComm::SetServerState(bool bServer)
{
if (!IsStart())
m_bServer = bServer;
}
///////////////////////////////////////////////////////////////////////////////
// SetSmartAddressing : Address is included with message
void CSocketComm::SetSmartAddressing(bool bSmartAddressing)
{
if (!IsStart())
m_bSmartAddressing = bSmartAddressing;
}
///////////////////////////////////////////////////////////////////////////////
// OnDataReceived
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// This function is PURE Virtual, you MUST overwrite it. This is
// called every time new data is available.
// PARAMETERS:
///////////////////////////////////////////////////////////////////////////////
void CSocketComm::OnDataReceived(const LPBYTE lpBuffer, DWORD dwCount)
{
}
///////////////////////////////////////////////////////////////////////////////
// OnEvent
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// This function reports events & errors
// PARAMETERS:
// UINT uEvent: can be one of the event value EVT_(events)
///////////////////////////////////////////////////////////////////////////////
void CSocketComm::OnEvent(UINT uEvent)
{
}
///////////////////////////////////////////////////////////////////////////////
// GetPortNumber
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Returns a port number based on service name or port number string
// PARAMETERS:
// LPCTSTR strServiceName: Service name or port string
///////////////////////////////////////////////////////////////////////////////
USHORT CSocketComm::GetPortNumber( LPCTSTR strServiceName )
{
LPSERVENT lpservent;
USHORT nPortNumber = 0;
if ( _istdigit( strServiceName[0] ) ) {
nPortNumber = (USHORT) _ttoi( strServiceName );
}
else {
#ifdef _UNICODE
char pstrService[HOSTNAME_SIZE];
WideCharToMultiByte(CP_ACP, 0, pstrService, -1, strServiceName, sizeof(pstrService), NULL, NULL );
#else
LPCTSTR pstrDevice = strServiceName;
#endif
// Convert network byte order to host byte order
if ( (lpservent = getservbyname( pstrDevice, NULL )) != NULL )
nPortNumber = ntohs( lpservent->s_port );
}
return nPortNumber;
}
///////////////////////////////////////////////////////////////////////////////
// GetIPAddress
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Returns an IP address.
// - It tries to convert the string directly
// - If that fails, it tries to resolve it as a hostname
// PARAMETERS:
// LPCTSTR strHostName: host name to get IP address
///////////////////////////////////////////////////////////////////////////////
ULONG CSocketComm::GetIPAddress( LPCTSTR strHostName )
{
LPHOSTENT lphostent;
ULONG uAddr = INADDR_NONE;
TCHAR strLocal[HOSTNAME_SIZE] = { 0 };
// if no name specified, get local
if ( NULL == strHostName )
{
GetLocalName(strLocal, sizeof(strLocal));
strHostName = strLocal;
}
#ifdef _UNICODE
char strHost[HOSTNAME_SIZE] = { 0 };
WideCharToMultiByte(CP_ACP, 0, strHostName, -1, strHost, sizeof(strHost), NULL, NULL );
#else
LPCTSTR strHost = strHostName;
#endif
// Check for an Internet Protocol dotted address string
uAddr = inet_addr( strHost );
if ( (INADDR_NONE == uAddr) && (strcmp( strHost, "255.255.255.255" )) )
{
// It's not an address, then try to resolve it as a hostname
if ( lphostent = gethostbyname( strHost ) )
uAddr = *((ULONG *) lphostent->h_addr_list[0]);
}
return ntohl( uAddr );
}
///////////////////////////////////////////////////////////////////////////////
// GetLocalName
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Get local computer name. Something like: "mycomputer.myserver.net"
// PARAMETERS:
// LPTSTR strName: name of the computer is returned here
// UINT nSize: size max of buffer "strName"
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::GetLocalName(LPTSTR strName, UINT nSize)
{
if (strName != NULL && nSize > 0)
{
char strHost[HOSTNAME_SIZE] = { 0 };
// get host name, if fail, SetLastError is set
if (SOCKET_ERROR != gethostname(strHost, sizeof(strHost)))
{
struct hostent* hp;
hp = gethostbyname(strHost);
if (hp != NULL) {
strcpy(strHost, hp->h_name);
}
// check if user provide enough buffer
if (strlen(strHost) > nSize)
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return false;
}
// Unicode conversion
#ifdef _UNICODE
return (0 != MultiByteToWideChar(CP_ACP, 0, strHost, -1, strName, nSize, NULL, NULL ));
#else
_tcscpy(strName, strHost);
return true;
#endif
}
}
else
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
///////////////////////////////////////////////////////////////////////////////
// GetLocalAddress
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Get TCP address of local computer in dot format ex: "127.0.0.0"
// PARAMETERS:
// LPTSTR strAddress: pointer to hold address string, must be long enough
// UINT nSize: maximum size of this buffer
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::GetLocalAddress(LPTSTR strAddress, UINT nSize)
{
// Get computer local address
if (strAddress != NULL && nSize > 0)
{
char strHost[HOSTNAME_SIZE] = { 0 };
// get host name, if fail, SetLastError is called
if (SOCKET_ERROR != gethostname(strHost, sizeof(strHost)))
{
struct hostent* hp;
hp = gethostbyname(strHost);
if (hp != NULL && hp->h_addr_list[0] != NULL)
{
// Address is four bytes (32-bit)
if ( hp->h_length < 4)
return false;
// Convert address to . format
strHost[0] = 0;
// Create Address string
sprintf(strHost, "%u.%u.%u.%u",
(UINT)(((PBYTE) hp->h_addr_list[0])[0]),
(UINT)(((PBYTE) hp->h_addr_list[0])[1]),
(UINT)(((PBYTE) hp->h_addr_list[0])[2]),
(UINT)(((PBYTE) hp->h_addr_list[0])[3]));
// check if user provide enough buffer
if (strlen(strHost) > nSize)
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return false;
}
// Unicode conversion
#ifdef _UNICODE
return (0 != MultiByteToWideChar(CP_ACP, 0, strHost, -1, strAddress,
nSize, NULL, NULL ));
#else
_tcscpy(strAddress, strHost);
return true;
#endif
}
}
}
else
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
///////////////////////////////////////////////////////////////////////////////
// WaitForConnection
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Wait for a network connection. Only for connection type of socket
// This function may fail, in this case it returns "INVALID_SOCKET"
// PARAMETERS:
// SOCKET sock: a socket capable of receiving new connection (TCP: SOCK_STREAM)
///////////////////////////////////////////////////////////////////////////////
SOCKET CSocketComm::WaitForConnection(SOCKET sock)
{
// Accept an incoming connection - blocking
// no information about remote address is returned
return accept(sock, 0, 0);
}
///////////////////////////////////////////////////////////////////////////////
// ShutdownConnection
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Shutdown a connection and close socket. This will force all
// transmission/reception to fail.
// PARAMETERS:
// SOCKET sock: Socket to close
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::ShutdownConnection(SOCKET sock)
{
shutdown(sock, SD_BOTH);
return ( 0 == closesocket( sock ));
}
///////////////////////////////////////////////////////////////////////////////
// GetSockName
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// retrieves the local name for a socket
// PARAMETERS:
// SockAddrIn& saddr_in: object to store address
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::GetSockName(SockAddrIn& saddr_in)
{
if (IsOpen())
{
int namelen = saddr_in.Size();
return (SOCKET_ERROR != getsockname(GetSocket(), (LPSOCKADDR)saddr_in, &namelen));
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// GetPeerName
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// retrieves the name of the peer to which a socket is connected
// PARAMETERS:
// SockAddrIn& saddr_in: object to store address
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::GetPeerName(SockAddrIn& saddr_in)
{
if (IsOpen())
{
int namelen = saddr_in.Size();
return (SOCKET_ERROR != getpeername(GetSocket(), (LPSOCKADDR)saddr_in, &namelen));
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// CreateSocket
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// This function creates a new socket for connection (SOCK_STREAM)
// or an connectionless socket (SOCK_DGRAM). A connectionless
// socket should not call "accept()" since it cannot receive new
// connection. This is used as SERVER socket
// PARAMETERS:
// LPCTSTR strServiceName: Service name or port number
// int nFamily: address family to use (set to AF_INET)
// int nType: type of socket to create (SOCK_STREAM, SOCK_DGRAM)
// UINT uOptions: other options to use
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::CreateSocket(LPCTSTR strServiceName, int nFamily, int nType, UINT uOptions /* = 0 */)
{
// Socket is already opened
if ( IsOpen() )
return false;
// Create a Socket that is bound to a specific service provide
// nFamily: (AF_INET)
// nType: (SOCK_STREAM, SOCK_DGRAM)
SOCKET sock = socket(nFamily, nType, 0);
if (INVALID_SOCKET != sock)
{
if (uOptions & SO_REUSEADDR)
{
// Inform Windows Sockets provider that a bind on a socket should not be disallowed
// because the desired address is already in use by another socket
BOOL optval = TRUE;
if ( SOCKET_ERROR == setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (char *) &optval, sizeof( BOOL ) ) )
{
closesocket( sock );
return false;
}
}
if (nType == SOCK_DGRAM)
{
if (uOptions & SO_BROADCAST)
{
// Inform Windows Sockets provider that broadcast messages are allowed
BOOL optval = TRUE;
if ( SOCKET_ERROR == setsockopt( sock, SOL_SOCKET, SO_BROADCAST, (char *) &optval, sizeof( BOOL ) ) )
{
closesocket( sock );
return false;
}
// we may proceed
m_bBroadcast = true;
}
// we need mutex only for UDP - broadcast socket
m_hMutex = CreateMutex(NULL, FALSE, NULL);
if (NULL == m_hMutex)
{
closesocket( sock );
return false;
}
}
// Associate a local address with the socket
SockAddrIn sockAddr;
sockAddr.CreateFrom(NULL, strServiceName, nFamily);
if ( SOCKET_ERROR == bind(sock, (LPSOCKADDR)sockAddr, sockAddr.Size()))
{
closesocket( sock );
m_bBroadcast = false;
if (NULL != m_hMutex)
CloseHandle( m_hMutex );
m_hMutex = NULL;
return false;
}
// Listen to the socket, only valid for connection socket
if (SOCK_STREAM == nType)
{
if ( SOCKET_ERROR == listen(sock, SOMAXCONN))
{
closesocket( sock );
return false;
}
}
// Success, now we may save this socket
m_hComm = (HANDLE) sock;
}
return (INVALID_SOCKET != sock);
}
///////////////////////////////////////////////////////////////////////////////
// ConnectTo
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Establish connection with a server service or port
// PARAMETERS:
// LPCTSTR strDestination: hostname or address to connect (in .dot format)
// LPCTSTR strServiceName: Service name or port number
// int nFamily: address family to use (set to AF_INET)
// int nType: type of socket to create (SOCK_STREAM, SOCK_DGRAM)
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::ConnectTo(LPCTSTR strDestination, LPCTSTR strServiceName, int nFamily, int nType)
{
// Socket is already opened
if ( IsOpen() )
return false;
// Create a Socket that is bound to a specific service provide
// nFamily: (AF_INET)
// nType: (SOCK_STREAM, SOCK_DGRAM)
SOCKET sock = socket(nFamily, nType, 0);
if (INVALID_SOCKET != sock)
{
// Associate a local address with the socket
SockAddrIn sockAddr;
if (false == sockAddr.CreateFrom(NULL, TEXT("0"), nFamily))
{
closesocket( sock );
return false;
}
if ( SOCKET_ERROR == bind(sock, (LPSOCKADDR)sockAddr, sockAddr.Size() ))
{
closesocket( sock );
return false;
}
// Now get destination address & port
sockAddr.CreateFrom( strDestination, strServiceName );
// try to connect - if fail, server not ready
if (SOCKET_ERROR == connect( sock, (LPSOCKADDR)sockAddr, sockAddr.Size()))
{
closesocket( sock );
return false;
}
// Success, now we may save this socket
m_hComm = (HANDLE) sock;
}
return (INVALID_SOCKET != sock);
}
///////////////////////////////////////////////////////////////////////////////
// CloseComm
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Close Socket Communication
// PARAMETERS:
// None
///////////////////////////////////////////////////////////////////////////////
void CSocketComm::CloseComm()
{
if (IsOpen())
{
ShutdownConnection((SOCKET)m_hComm);
m_hComm = INVALID_HANDLE_VALUE;
m_bBroadcast = false;
}
}
///////////////////////////////////////////////////////////////////////////////
// WatchComm
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Starts Socket Communication Working thread
// PARAMETERS:
// None
///////////////////////////////////////////////////////////////////////////////
bool CSocketComm::WatchComm()
{
if (!IsStart())
{
if (IsOpen())
{
HANDLE hThread;
UINT uiThreadId = 0;
hThread = (HANDLE)_beginthreadex(NULL, // Security attributes
0, // stack
SocketThreadProc, // Thread proc
this, // Thread param
CREATE_SUSPENDED, // creation mode
&uiThreadId); // Thread ID
if ( NULL != hThread)
{
//SetThreadPriority(hThread, THREAD_PRIORITY_HIGHEST);
ResumeThread( hThread );
m_hThread = hThread;
return true;
}
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// StopComm
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Close Socket and Stop Communication thread
// PARAMETERS:
// None
///////////////////////////////////////////////////////////////////////////////
void CSocketComm::StopComm()
{
// Close Socket
if (IsOpen())
{
CloseComm();
Sleep(50);
}
// Kill Thread
if (IsStart())
{
if (WaitForSingleObject(m_hThread, 5000L) == WAIT_TIMEOUT)
TerminateThread(m_hThread, 1L);
CloseHandle(m_hThread);
m_hThread = NULL;
}
// Clear Address list
if (!m_AddrList.empty())
m_AddrList.clear();
// Destroy Synchronization objects
if (NULL != m_hMutex)
{
CloseHandle( m_hMutex );
m_hMutex = NULL;
}
}
///////////////////////////////////////////////////////////////////////////////
// ReadComm
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Reads the Socket Communication
// PARAMETERS:
// LPBYTE lpBuffer: buffer to place new data
// DWORD dwSize: maximum size of buffer
// DWORD dwTimeout: timeout to use in millisecond
///////////////////////////////////////////////////////////////////////////////
DWORD CSocketComm::ReadComm(LPBYTE lpBuffer, DWORD dwSize, DWORD dwTimeout)
{
_ASSERTE( IsOpen() );
_ASSERTE( lpBuffer != NULL );
if (lpBuffer == NULL || dwSize < 1L)
return 0L;
fd_set fdRead = { 0 };
TIMEVAL stTime;
TIMEVAL *pstTime = NULL;
if ( INFINITE != dwTimeout ) {
stTime.tv_sec = dwTimeout/1000;
stTime.tv_usec = dwTimeout % 1000;
pstTime = &stTime;
}
SOCKET s = (SOCKET) m_hComm;
// Set Descriptor
if ( !FD_ISSET( s, &fdRead ) )
FD_SET( s, &fdRead );
// Select function set read timeout
DWORD dwBytesRead = 0L;
int res = select( s+1, &fdRead, NULL, NULL, pstTime );
if ( res > 0)
{
if (IsBroadcast() || IsSmartAddressing())
{
SockAddrIn sockAddr;
int nLen = sockAddr.Size();
int nOffset = IsSmartAddressing() ? nLen : 0; // use offset for Smart addressing
if ( dwSize < (DWORD) nOffset) // error - buffer to small
{
SetLastError( ERROR_INVALID_USER_BUFFER );
return -1L;
}
LPSTR lpszData = (LPSTR)(lpBuffer + nOffset);
res = recvfrom( s, lpszData, dwSize-nOffset, 0, (LPSOCKADDR)sockAddr, &nLen);
// clear 'sin_zero', we will ignore them with 'SockAddrIn' anyway!
memset(&sockAddr.sin_zero, 0, sizeof(sockAddr.sin_zero));
// Lock the list...
LockList();
m_AddrList.remove( sockAddr );
if ( res >= 0)
{
// insert unique address
m_AddrList.insert(m_AddrList.end(), sockAddr);
if (IsSmartAddressing())
{
memcpy(lpBuffer, &sockAddr, sockAddr.Size());
res += sockAddr.Size();
}
}
UnlockList(); // unlock this object addresses-list
}
else
{
res = recv( s, (LPSTR)lpBuffer, dwSize, 0);
}
dwBytesRead = (DWORD)((res > 0)?(res) : (-1L));
}
return dwBytesRead;
}
///////////////////////////////////////////////////////////////////////////////
// WriteComm
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// Writes data to the Socket Communication
// PARAMETERS:
// const LPBYTE lpBuffer: data to write
// DWORD dwCount: maximum characters to write
// DWORD dwTimeout: timeout to use in millisecond
///////////////////////////////////////////////////////////////////////////////
DWORD CSocketComm::WriteComm(const LPBYTE lpBuffer, DWORD dwCount, DWORD dwTimeout)
{
_ASSERTE( IsOpen() );
_ASSERTE( NULL != lpBuffer );
// Accept 0 bytes message
if (!IsOpen() || NULL == lpBuffer)
return 0L;
fd_set fdWrite = { 0 };
TIMEVAL stTime;
TIMEVAL *pstTime = NULL;
if ( INFINITE != dwTimeout ) {
stTime.tv_sec = dwTimeout/1000;
stTime.tv_usec = dwTimeout % 1000;
pstTime = &stTime;
}
SOCKET s = (SOCKET) m_hComm;
// Set Descriptor
if ( !FD_ISSET( s, &fdWrite ) )
FD_SET( s, &fdWrite );
// Select function set write timeout
DWORD dwBytesWritten = 0L;
int res = select( s+1, NULL, &fdWrite, NULL, pstTime );
if ( res > 0)
{
// Send message to peer or broadcast it
if (IsBroadcast() || IsSmartAddressing())
{
// use offset for Smart addressing
int nOffset = IsSmartAddressing() ? sizeof(SOCKADDR_IN) : 0;
if (IsSmartAddressing())
{
if ( dwCount < sizeof(SOCKADDR_IN)) // error - buffer to small
{
SetLastError( ERROR_INVALID_USER_BUFFER );
return -1L;
}
// read socket address from buffer
SockAddrIn sockAddr;
sockAddr.SetAddr((PSOCKADDR_IN) lpBuffer);
// Get Address and send data
if (sockAddr.sin_addr.s_addr != htonl(INADDR_BROADCAST))
{
LPSTR lpszData = (LPSTR)(lpBuffer + nOffset);
res = sendto( s, lpszData, dwCount-nOffset, 0,
(LPSOCKADDR)sockAddr, sockAddr.Size());
dwBytesWritten = (DWORD)((res >= 0)?(res) : (-1));
return dwBytesWritten;
}
}
// Broadcast send to all connected-peer
LockList(); // Lock this object addresses-list
CSockAddrList::iterator iter = m_AddrList.begin();
for( ; iter != m_AddrList.end(); )
{
// Fix v1.3 - nOffset was missing
res = sendto( s, (LPCSTR)&lpBuffer[nOffset], dwCount-nOffset, 0, (LPSOCKADDR)(*iter), iter->Size());
if (res < 0)
{
CSockAddrList::iterator deladdr = iter;
++iter; // get next
m_AddrList.erase( deladdr );
}
else
++iter; // get next
}
UnlockList(); // unlock this object addresses-list
// always return success - UDP
res = (int) dwCount - nOffset;
}
else // Send to peer-connection
res = send( s, (LPCSTR)lpBuffer, dwCount, 0);
dwBytesWritten = (DWORD)((res >= 0)?(res) : (-1));
}
return dwBytesWritten;
}
///////////////////////////////////////////////////////////////////////////////
// Run
///////////////////////////////////////////////////////////////////////////////
// DESCRIPTION:
// This function runs the main thread loop
// this implementation can be overloaded.
// This function calls CSocketComm::OnDataReceived() (Virtual Function)
// PARAMETERS:
// NOTES:
// You should not wait on the thread to end in this function or overloads
///////////////////////////////////////////////////////////////////////////////
void CSocketComm::Run()
{
stMessageProxy stMsgProxy;
DWORD dwBytes = 0L;
DWORD dwTimeout = DEFAULT_TIMEOUT;
LPBYTE lpData = (LPBYTE)&stMsgProxy;
DWORD dwSize = sizeof(stMsgProxy);
if (!IsSmartAddressing())
{
lpData = stMsgProxy.data;
dwSize = sizeof(stMsgProxy.data);
}
// Should we run as server mode
if (IsServer())
{
if (!IsBroadcast())
{
SOCKET sock = (SOCKET) m_hComm;
sock = WaitForConnection( sock );
// Get new connection socket
if (sock != INVALID_SOCKET)
{
ShutdownConnection( (SOCKET) m_hComm);
m_hComm = (HANDLE) sock;
OnEvent( EVT_CONSUCCESS ); // connect
}
else
{
// Do not send event if we are closing
if (IsOpen())
OnEvent( EVT_CONFAILURE ); // wait fail
return;
}
}
}
else
GetPeerName( stMsgProxy.address );
while( IsOpen() )
{
// Blocking mode: Wait for event
dwBytes = ReadComm(lpData, dwSize, dwTimeout);
// Error? - need to signal error
if (dwBytes == (DWORD)-1L)
{
// Do not send event if we are closing
if (IsOpen())
OnEvent( EVT_CONDROP ); // lost connection
// special case for UDP, alert about the event but do not stop
if (IsBroadcast())
continue;
else
break;
}
// Chars received?
if (IsSmartAddressing() && dwBytes == sizeof(SOCKADDR_IN))
OnEvent( EVT_ZEROLENGTH );
else if (dwBytes > 0L)
{
OnDataReceived( lpData, dwBytes);
}
Sleep(0);
}
}