IClientImpl.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. #include "StdAfx.h"
  2. #include "IClientImpl.h"
  3. #include <comdef.h>
  4. #include <atlbase.h>
  5. //#include "crc32.h"
  6. //#include "ThreadPool.hpp"
  7. #include "lzari.h"
  8. const int AF_IPV4 = 0;
  9. const int AF_IPV6 = 1;
  10. const int SOCK_TCP = SOCK_STREAM-1;
  11. const int SOCK_UDP = SOCK_DGRAM-1;
  12. //DWORD g_dwLeng = 0;
  13. //BYTE *g_pData = NULL;
  14. DWORD g_dwLeng2 = 0;
  15. extern BYTE *g_pData2;
  16. DWORD g_dwcount;
  17. BOOL g_bConnLYFZ = 0;
  18. int g_conntype = 0;//正常
  19. void IClientImpl::DataToArray(IN BYTE *pData, IN CONST DWORD &dwLength, IN CArray<CStringArray, CStringArray>*List1array)
  20. {
  21. List1array->RemoveAll();
  22. if (dwLength == 0)return;
  23. if (m_tSendhead.code[0])
  24. {
  25. BYTE *lpszOut = NULL;
  26. int nOutSize = 0;
  27. LZARI Lzari;
  28. Lzari.UnCompress(pData, dwLength, (const BYTE*&)lpszOut, nOutSize);
  29. CMemFile memfile;
  30. memfile.Attach(lpszOut, nOutSize);
  31. Lzari.Release();
  32. try
  33. {
  34. CArchive ar(&memfile, CArchive::load);
  35. List1array->SetSize(m_tSendhead.count[0]);
  36. for (int i = 0; i < List1array->GetSize(); i++)
  37. {
  38. List1array->ElementAt(i).Serialize(ar);
  39. }
  40. ar.Close();
  41. memfile.Detach();
  42. }
  43. catch (CException* e)
  44. {
  45. e->ReportError();
  46. }
  47. }
  48. else
  49. {
  50. CMemFile memfile;
  51. memfile.Attach(pData, dwLength);
  52. CArchive ar(&memfile, CArchive::load);
  53. List1array->SetSize(m_tSendhead.count[0]);
  54. for (int ii = 0; ii < List1array->GetSize(); ii++)
  55. {
  56. List1array->ElementAt(ii).Serialize(ar);
  57. }
  58. ar.Close();
  59. memfile.Detach();
  60. }
  61. }
  62. //IClientImpl* IClientImpl::m_pTcpClient[TCPCLIENTNUM] = {NULL};
  63. void GetFileName(IN const TCHAR *pFullName,OUT TCHAR *pFileName)
  64. {
  65. TCHAR szExt[_MAX_EXT];
  66. _tsplitpath(pFullName, NULL, NULL, pFileName, szExt);
  67. _tcscat(pFileName, szExt);
  68. }
  69. IClientImpl::IClientImpl():m_nMode(AF_IPV4),m_nSockType(SOCK_TCP)
  70. {
  71. m_bSocket = FALSE;
  72. m_bStopbeat = FALSE;
  73. m_hRunObject = NULL;
  74. m_bRecevie = TRUE;
  75. m_hReConnectSrvThreadHandle = NULL;
  76. m_dwSumRecive = 0;
  77. m_dwCurRecive = 0;
  78. m_pRecivebuf = NULL;
  79. ZeroMemory(&m_tSendhead, sizeof(SENDHEAD));
  80. m_SocketClient.SetInterface(this);
  81. }
  82. IClientImpl::~IClientImpl()
  83. {
  84. //m_SocketClient.Terminate();
  85. net_CloseSocket();
  86. }
  87. BOOL IClientImpl::SolveDBError()
  88. {
  89. DWORD dwWSAError = WSAGetLastError();
  90. if ( dwWSAError != 0 )
  91. {
  92. //LOG4C_NO_FILENUM((LOG_NOTICE,"dwWSAError = %d~",dwWSAError));
  93. }
  94. switch(dwWSAError)
  95. {
  96. case WSAENOTSOCK:
  97. case WSAENETDOWN:
  98. case WSAENETUNREACH:
  99. case WSAENETRESET:
  100. case WSAECONNABORTED:
  101. case WSAECONNRESET:
  102. case WSAESHUTDOWN:
  103. case WSAEHOSTDOWN:
  104. case WSAEHOSTUNREACH:
  105. TRACE("-----------------WSAError = %d\n",dwWSAError);
  106. //LOG4C_NO_FILENUM((LOG_NOTICE,"dwWSAError = %d~",dwWSAError));
  107. m_bSocket = FALSE;
  108. break;
  109. default:
  110. break;
  111. }
  112. return TRUE;
  113. }
  114. void IClientImpl::GetAddress(const SockAddrIn& addrIn, CString& rString) const
  115. {
  116. TCHAR szIPAddr[MAX_PATH] = { 0 };
  117. CSocketHandle::FormatIP(szIPAddr, MAX_PATH, addrIn);
  118. rString.Format(_T("%s : %d"), szIPAddr, static_cast<int>(static_cast<UINT>(ntohs(addrIn.GetPort()))) );
  119. }
  120. void IClientImpl::AppendText(LPCTSTR lpszFormat, ...)
  121. {
  122. // if ( !::IsWindow(m_ctlMsgList.GetSafeHwnd()) ) return;
  123. // TCHAR szBuffer[512];
  124. // HWND hWnd = m_ctlMsgList.GetSafeHwnd();
  125. // DWORD dwResult = 0;
  126. // if (SendMessageTimeout(hWnd, WM_GETTEXTLENGTH, 0, 0, SMTO_NORMAL, 500L, &dwResult) != 0)
  127. // {
  128. // int nLen = (int) dwResult;
  129. // if (SendMessageTimeout(hWnd, EM_SETSEL, nLen, nLen, SMTO_NORMAL, 500L, &dwResult) != 0)
  130. // {
  131. // size_t cb = 0;
  132. // va_list args;
  133. // va_start(args, lpszFormat);
  134. // ::StringCchVPrintfEx(szBuffer, 512, NULL, &cb, 0, lpszFormat, args);
  135. // va_end(args);
  136. // SendMessageTimeout(hWnd, EM_REPLACESEL, FALSE, reinterpret_cast<LPARAM>(szBuffer), SMTO_NORMAL, 500L, &dwResult);
  137. // }
  138. // }
  139. }
  140. bool IClientImpl::GetDestination(SockAddrIn& addrIn) const
  141. {
  142. CString strPort;
  143. int nFamily = (m_nMode == AF_IPV4) ? AF_INET : AF_INET6;
  144. return addrIn.CreateFrom(NULL, strPort, nFamily);
  145. }
  146. bool IClientImpl::SetupMCAST()
  147. {
  148. const TCHAR szIPv4MCAST[] = TEXT("239.121.1.2");
  149. const TCHAR szIPv6MCAST[] = TEXT("FF02:0:0:0:0:0:0:1"); // All Nodes local address
  150. bool result = false;
  151. if ( m_nSockType == SOCK_UDP )
  152. {
  153. if ( m_nMode == AF_IPV4 ) {
  154. result = m_SocketClient->AddMembership(szIPv4MCAST, NULL);
  155. } else {
  156. result = m_SocketClient->AddMembership(szIPv6MCAST, NULL);
  157. HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  158. hr = hr;
  159. }
  160. }
  161. return result;
  162. }
  163. ///////////////////////////////////////////////////////////////////////////////
  164. void IClientImpl::OnThreadBegin(CSocketHandle* pSH)
  165. {
  166. ASSERT( pSH == m_SocketClient );
  167. (pSH);
  168. CString strAddr;
  169. SockAddrIn sockAddr;
  170. m_SocketClient->GetSockName(sockAddr);
  171. GetAddress( sockAddr, strAddr );
  172. }
  173. void IClientImpl::OnThreadExit(CSocketHandle* pSH)
  174. {
  175. ASSERT( pSH == m_SocketClient );
  176. (pSH);
  177. }
  178. void IClientImpl::OnConnectionDropped(CSocketHandle* pSH)
  179. {
  180. ASSERT( pSH == m_SocketClient );
  181. m_bSocket = FALSE;
  182. AppendText( _T("Connection lost with client.\r\n") );
  183. }
  184. void IClientImpl::OnConnectionError(CSocketHandle* pSH, DWORD dwError)
  185. {
  186. ASSERT( pSH == m_SocketClient );
  187. (pSH);
  188. _com_error err(dwError);
  189. AppendText( _T("Communication Error:\r\n%s\r\n"), err.ErrorMessage() );
  190. }
  191. /************************************************************************/
  192. /* 函数:OnDataReceived[3/21/2016 IT];
  193. /* 描述:;
  194. /* 参数:;
  195. /* [IN] pSH: 客户端实例对象;
  196. /* [IN] pbData: 客户端本次接收到的数据;
  197. /* [IN] dwCount: 客户端本次接收到的数据长度;
  198. /* [IN] addr: 服务端地址;
  199. /* 返回:void;
  200. /* 注意:;
  201. /* 示例:;
  202. /*
  203. /* 修改:;
  204. /* 日期:;
  205. /* 内容:;
  206. /************************************************************************/
  207. void IClientImpl::OnDataReceived(CSocketHandle* pSH, const BYTE* pbData, DWORD dwCount, const SockAddrIn& addr)
  208. {
  209. ASSERT( pSH == m_SocketClient );
  210. if( !m_SocketClient->IsOpen() ) return;
  211. if (NULL == pbData) return;
  212. if ( m_pRecivebuf )
  213. {// 有上次接收的余包,认为服务分包发送数据,重新组包;
  214. if ( m_dwSumRecive < m_dwCurRecive + dwCount )
  215. {
  216. if ( m_pRecivebuf )
  217. delete []m_pRecivebuf;
  218. m_pRecivebuf = NULL;
  219. m_dwCurRecive = m_dwSumRecive = 0;
  220. m_bRecevie = TRUE;
  221. }
  222. memcpy(m_pRecivebuf + m_dwCurRecive, pbData, dwCount);
  223. m_dwCurRecive += dwCount;
  224. if ( m_dwCurRecive == m_dwSumRecive )
  225. {// 组包完整,回调处理;
  226. TRACE("完包Tickets = %d \n", GetTickCount());
  227. m_eventHandler(pSH->GetSocket(), Transport_ReadEv, m_pRecivebuf, m_dwSumRecive, 0, m_pContext);
  228. if ( m_pRecivebuf )
  229. delete []m_pRecivebuf;
  230. m_pRecivebuf = NULL;
  231. m_dwCurRecive = m_dwSumRecive = 0;
  232. }
  233. return;
  234. }
  235. TMessageHeader* pHeader = (TMessageHeader *)pbData;
  236. // 网络字节顺序的转换;
  237. ntohs(pHeader->wHeaderFlag);
  238. ntohs(pHeader->wMessageId);
  239. ntohs(pHeader->wMessageSubId);
  240. ntohl(pHeader->dwDataLen);
  241. ntohs(pHeader->wCheckSum);
  242. ntohl(pHeader->wReserve);
  243. if ( pHeader->dwDataLen + MESSAGE_HEADER_LEN > dwCount )
  244. {// 服务器分包发送;
  245. OutputDebugString(_T("服务器分包发送:"));
  246. DWORD dwTick = GetTickCount();
  247. TRACE("当前Tickets = %d \n", dwTick);
  248. if ( m_pRecivebuf )
  249. {
  250. delete []m_pRecivebuf;
  251. m_pRecivebuf = NULL;
  252. m_dwSumRecive = m_dwCurRecive = 0;
  253. }
  254. m_dwSumRecive = pHeader->dwDataLen + MESSAGE_HEADER_LEN;
  255. m_pRecivebuf = new BYTE[m_dwSumRecive];
  256. memset(m_pRecivebuf, 0 , m_dwSumRecive);
  257. memcpy(m_pRecivebuf + m_dwCurRecive, pbData, dwCount);
  258. m_dwCurRecive += dwCount;
  259. }
  260. else
  261. {// 服务器未分包发,包完整;
  262. m_eventHandler(pSH->GetSocket(), Transport_ReadEv, (void*)pbData, dwCount, 0, m_pContext);
  263. }
  264. }
  265. BOOL IClientImpl::Initialize()
  266. {
  267. TCHAR szIPAddr[MAX_PATH] = { 0 };
  268. CSocketHandle::GetLocalAddress(szIPAddr, MAX_PATH, AF_INET);
  269. AppendText(_T("Local Address (IPv4): %s\r\n"), szIPAddr);
  270. CSocketHandle::GetLocalAddress(szIPAddr, MAX_PATH, AF_INET6);
  271. AppendText(_T("Local Address (IPv6): %s\r\n"), szIPAddr);
  272. return TRUE;
  273. }
  274. void IClientImpl::StartReConnectSrvThread()
  275. {
  276. // Jeff.启用重连服务端线程.-------------------
  277. m_hRunObject = CreateEvent( NULL, TRUE, FALSE, _T("ClientThreadRun") );
  278. if ( m_hRunObject == NULL )
  279. {
  280. //LOG4C((LOG_NOTICE,"创建事件失败"));
  281. }
  282. m_hReConnectSrvThreadHandle = CreateThread(NULL,0,ReConnectSrvThread,this,0,NULL);
  283. if ( m_hReConnectSrvThreadHandle == NULL )
  284. {
  285. //LOG4C((LOG_NOTICE,"创建线程失败"));
  286. }
  287. }
  288. BOOL IClientImpl::ConnectServer(LPCTSTR strAddr, LPCTSTR strPort)
  289. {
  290. _stprintf_s(m_SvrAddr,_T("%s"),strAddr);
  291. _stprintf_s(m_SvrPort,_T("%s"),strPort);
  292. int nFamily = (m_nMode == AF_IPV4) ? AF_INET : AF_INET6;
  293. if ( !m_SocketClient.StartClient(NULL, strAddr, strPort, nFamily, (m_nSockType+1) ) )
  294. {
  295. m_bSocket = FALSE;
  296. return FALSE;
  297. }
  298. return TRUE;
  299. }
  300. void IClientImpl::net_CloseSocket()
  301. {
  302. if(m_hRunObject)
  303. SetEvent(m_hRunObject);
  304. if( m_hReConnectSrvThreadHandle )
  305. {
  306. if (WaitForSingleObject(m_hReConnectSrvThreadHandle,INFINITE) != WAIT_FAILED)
  307. {
  308. CloseHandle(m_hReConnectSrvThreadHandle);
  309. m_hReConnectSrvThreadHandle = NULL;
  310. }
  311. }
  312. if(m_hRunObject)
  313. CloseHandle( m_hRunObject );
  314. m_hRunObject = NULL;
  315. m_SocketClient.Terminate();
  316. }
  317. void IClientImpl::SendMsg(void *pMsg,const int nLen)
  318. {
  319. if ( m_SocketClient.IsOpen() )
  320. {
  321. USES_CONVERSION;
  322. if (m_nSockType == SOCK_TCP)
  323. {
  324. m_SocketClient.Write((const LPBYTE)(pMsg), nLen, NULL, 30000);
  325. }
  326. else
  327. {
  328. SockAddrIn sockAddr;
  329. GetDestination(sockAddr);
  330. m_SocketClient.Write((const LPBYTE)(pMsg), nLen, sockAddr, 30000);
  331. }
  332. }
  333. else
  334. {
  335. AfxMessageBox(_T("Socket is not connected"));
  336. }
  337. }
  338. DWORD WINAPI IClientImpl::ReConnectSrvThread(LPVOID pInstance)
  339. {
  340. IClientImpl *pClientImpl = (IClientImpl*)pInstance;
  341. do
  342. {
  343. // 检测连接状态;
  344. if ( pClientImpl->m_bSocket == FALSE )
  345. {
  346. if ( pClientImpl->m_SocketClient->IsOpen() == TRUE )
  347. {
  348. pClientImpl->m_SocketClient.Terminate();
  349. }
  350. pClientImpl->m_bSocket = pClientImpl->ConnectServer(pClientImpl->m_SvrAddr,pClientImpl->m_SvrPort);
  351. }
  352. } while( WaitForSingleObject(pClientImpl->m_hRunObject,200L) == WAIT_TIMEOUT );
  353. //LOG4C_NO_FILENUM((LOG_NOTICE,"重连服务器线程退出"));
  354. return 0;
  355. }
  356. //////////////////////////////////////////////////////////////////////////
  357. BOOL IClientImpl::net_Connect(LPCTSTR strAddr, LPCTSTR strPort)
  358. {
  359. _stprintf_s(m_SvrAddr,_T("%s"),strAddr);
  360. _stprintf_s(m_SvrPort,_T("%s"),strPort);
  361. int nFamily = (m_nMode == AF_IPV4) ? AF_INET : AF_INET6;
  362. if ( !m_SocketClient.StartClient(NULL, strAddr, strPort, nFamily, (m_nSockType+1) ) )
  363. {
  364. m_bSocket = FALSE;
  365. return FALSE;
  366. }
  367. else
  368. {
  369. m_bSocket = TRUE;
  370. SetupMCAST();
  371. return TRUE;
  372. }
  373. }
  374. DWORD IClientImpl::net_Send(IN void *pHeader, IN void *pMessage, IN CONST unsigned long ulDataLen)
  375. {
  376. unsigned long ulSendLen = 0;
  377. unsigned long ulBufLen = 0;
  378. TMessageHeader *pSendHeader = (TMessageHeader *)pHeader;
  379. ulBufLen = MESSAGE_HEADER_LEN + ulDataLen;
  380. char *pSendBuf = new char[ulBufLen];
  381. memset(pSendBuf, 0, ulBufLen);
  382. TMessageHeader *pMessageHeader = (TMessageHeader *)pSendBuf;
  383. pMessageHeader->byVersion = 101;
  384. pMessageHeader->wHeaderFlag = MESSAGE_HEADER_FLAG;
  385. pMessageHeader->wMessageId = pSendHeader->wMessageId;
  386. pMessageHeader->wMessageSubId = pSendHeader->wMessageSubId;
  387. pMessageHeader->dwDataLen = ulDataLen;
  388. pMessageHeader->wReserve = 0;
  389. memcpy((void *)(pSendBuf+MESSAGE_HEADER_LEN), pMessage, ulDataLen);
  390. /* convert network word */
  391. htons(pMessageHeader->wHeaderFlag);
  392. htons(pMessageHeader->wMessageId);
  393. htons(pMessageHeader->wMessageSubId);
  394. htonl(pMessageHeader->dwDataLen);
  395. htons(pMessageHeader->wCheckSum);
  396. htonl(pMessageHeader->wReserve);
  397. ulSendLen = m_SocketClient->Write((LPBYTE)pSendBuf, ulBufLen, NULL, 30000);
  398. delete [] pSendBuf;
  399. pSendBuf = NULL;
  400. return ulSendLen;
  401. }
  402. INT IClientImpl::net_OpenSocket( IN CONST INT& nType, IN CONST DWORD& dwPort, IN LPTRANSPORT_EVENT eventHandler, void *pContext )
  403. {
  404. m_eventHandler = eventHandler;
  405. m_pContext = pContext;
  406. return 0;
  407. }