WatchServerSocket.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. #include "stdafx.h"
  2. #include <atlbase.h>
  3. //#include "Client2SrvType.h"
  4. #include "Global.h"
  5. #include "WatchServerSocket.h"
  6. #include "crc32.h"
  7. #pragma warning(push)
  8. #pragma warning(disable:4995)
  9. #pragma warning(pop)
  10. const int AF_IPV4 = 0;
  11. const int AF_IPV6 = 1;
  12. const int SOCK_TCP = SOCK_STREAM-1;
  13. const int SOCK_UDP = SOCK_DGRAM-1;
  14. //---------------------------------------------- CWatchServerSocket ----
  15. CWatchServerSocket::CWatchServerSocket()
  16. {
  17. m_nMode = AF_IPV4;
  18. m_nSockType = SOCK_TCP;
  19. m_SocketClient.SetInterface(this);
  20. m_bSocket = FALSE;
  21. }
  22. CWatchServerSocket::~CWatchServerSocket()
  23. {
  24. }
  25. BOOL CWatchServerSocket::Connection(LPCTSTR strAddr, LPCTSTR strPort)
  26. {
  27. int nFamily = (m_nMode == AF_IPV4) ? AF_INET : AF_INET6;
  28. if ( !m_SocketClient.StartClient(NULL, strAddr, strPort, nFamily, (m_nSockType+1) ) )
  29. {
  30. //MessageBox(NULL, _T("连接服务器失败!"), "提示", MB_ICONSTOP);
  31. return FALSE;
  32. }
  33. else
  34. {
  35. CSocketHandle* pSH = (CSocketHandle *)m_SocketClient;
  36. pSH->m_nPendingSize = 0;
  37. memset(pSH->m_PendingBuffer, 0, SOCKET_BUFFSIZE);
  38. SetupMCAST();
  39. return TRUE;
  40. }
  41. }
  42. void CWatchServerSocket::DisConnection()
  43. {
  44. m_SocketClient.Terminate();
  45. Sleep(1000);
  46. }
  47. bool CWatchServerSocket::SetupMCAST()
  48. {
  49. const TCHAR szIPv4MCAST[] = TEXT("239.121.1.2");
  50. const TCHAR szIPv6MCAST[] = TEXT("FF02:0:0:0:0:0:0:1"); // All Nodes local address
  51. bool result = false;
  52. if ( m_nSockType == SOCK_UDP )
  53. {
  54. if ( m_nMode == AF_IPV4 ) {
  55. result = m_SocketClient->AddMembership(szIPv4MCAST, NULL);
  56. } else {
  57. result = m_SocketClient->AddMembership(szIPv6MCAST, NULL);
  58. HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  59. hr = hr;
  60. }
  61. }
  62. return result;
  63. }
  64. void CWatchServerSocket::GetAddress(const SockAddrIn& addrIn, CString& rString) const
  65. {
  66. TCHAR szIPAddr[MAX_PATH] = { 0 };
  67. CSocketHandle::FormatIP(szIPAddr, MAX_PATH, addrIn);
  68. rString.Format(_T("%s : %d"), szIPAddr, static_cast<int>(static_cast<UINT>(ntohs(addrIn.GetPort()))) );
  69. }
  70. ///////////////////////////////////////////////////////////////////////////////
  71. // 实现ISocketClientHandler的通信方法
  72. void CWatchServerSocket::OnThreadBegin(CSocketHandle* pSH)
  73. {
  74. ASSERT( pSH == m_SocketClient );
  75. (pSH);
  76. CString strAddr;
  77. SockAddrIn sockAddr;
  78. m_SocketClient->GetSockName(sockAddr);
  79. GetAddress( sockAddr, strAddr );
  80. InitializeCriticalSection(&pSH->m_hClient2SrvSection);
  81. // AppendText( _T("Client Running on: %s\r\n"), strAddr);
  82. }
  83. void CWatchServerSocket::OnThreadExit(CSocketHandle* pSH)
  84. {
  85. ASSERT( pSH == m_SocketClient );
  86. DeleteCriticalSection( &pSH->m_hClient2SrvSection );
  87. (pSH);
  88. }
  89. void CWatchServerSocket::OnDataReceived(CSocketHandle* pSH, const BYTE* pbData, DWORD dwCount, const SockAddrIn& addr)
  90. {
  91. ASSERT( pSH == m_SocketClient );
  92. (pSH);
  93. if( !m_SocketClient->IsOpen() ) return;
  94. ProcessData( pSH, pbData, dwCount );
  95. //int nRet;
  96. //nRet = OnCmdProcess( (void *)pbData );
  97. //if( nRet == -1 )
  98. //{
  99. // TRACE("crc32 error \r\n");
  100. //}
  101. }
  102. void CWatchServerSocket::OnConnectionDropped(CSocketHandle* pSH)
  103. {
  104. ASSERT( pSH == m_SocketClient );
  105. (pSH);
  106. m_bSocket = FALSE;
  107. LogEvent( _T("Connection lost with server. Need restart.\r\n") );
  108. }
  109. void CWatchServerSocket::OnConnectionError(CSocketHandle* pSH, DWORD dwError)
  110. {
  111. ASSERT( pSH == m_SocketClient );
  112. (pSH);
  113. //_com_error err(dwError);
  114. m_bSocket = FALSE;
  115. //LogEvent( _T("Communication Error:\r\n%s\r\n"), err.ErrorMessage() );
  116. }
  117. unsigned int CWatchServerSocket::CalcCheckSum( void *pData, unsigned int nSize )
  118. {
  119. unsigned int checksum = 0;
  120. if ( nSize <= sizeof( ProtocolHeader ) )
  121. {
  122. return 0;
  123. }
  124. unsigned char *pBody = &( ( unsigned char* )pData )[ sizeof( ProtocolHeader ) ];
  125. nSize -= sizeof( ProtocolHeader );
  126. checksum = crc32( 0, pBody, nSize );
  127. return checksum;
  128. }
  129. void CWatchServerSocket::ProcessHeart(void *pData, int nLen)
  130. {
  131. //m_SocketClient->Write((const LPBYTE)pData, nLen, NULL);
  132. ProtocolHeader *pHeader = (ProtocolHeader *)pData;
  133. if( pHeader != NULL )
  134. {
  135. if( pHeader->nCmdType >= 0 && pHeader->nCmdType < MAX_DLL_TYPE )
  136. {
  137. g_dwServiceOnlineTick[pHeader->nCmdType] = GetTickCount();
  138. //CString str;
  139. //str.Format("动态库类型=%d, 收到心跳包", pHeader->nCmdType);
  140. //LogEvent(str);
  141. }
  142. }
  143. //LogEvent("收到心跳包");
  144. }
  145. int CWatchServerSocket::OnCmdProcess(void *pData)
  146. {
  147. ProtocolHeader *pHeader = (ProtocolHeader *)pData;
  148. if( pHeader == NULL ) return -1;
  149. if( pHeader->nLen < 0 || pHeader->nLen > 65535 ) return -1;
  150. switch( pHeader->nCmd )
  151. {
  152. case CMD_WATCH_HEART:
  153. ProcessHeart(pData, pHeader->nLen);
  154. break;
  155. }
  156. return 0;
  157. }
  158. void CWatchServerSocket::ProcessData(CSocketHandle *pSH, const BYTE* pData, DWORD nLen)
  159. {
  160. DWORD nBuffIndex = 0;
  161. EnterCriticalSection( &(pSH->m_hClient2SrvSection) );
  162. while( nBuffIndex < nLen )
  163. {
  164. ProtocolHeader *pHeader; //当前协议包头
  165. DWORD nProcessedLen = 0; //当前循环处理了多少个字节
  166. if( pSH->m_nPendingSize > 0 ) // 开始组包
  167. {
  168. pHeader = (ProtocolHeader *)pSH->m_PendingBuffer;
  169. if( pSH->m_nPendingSize < sizeof(ProtocolHeader) ) //上一次接收到的长度小于包头
  170. {
  171. DWORD nLinkHeaderLen = sizeof( ProtocolHeader ) - pSH->m_nPendingSize;
  172. if( nLinkHeaderLen <= nLen ) //这次可以收完包头
  173. {
  174. memcpy( &pSH->m_PendingBuffer[ pSH->m_nPendingSize ], pData, nLinkHeaderLen ); //这里已经收完Header
  175. nProcessedLen = pHeader->nLen - pSH->m_nPendingSize;
  176. if( nProcessedLen <= nLen ) //如果所需处理的长度小于等于当前包长度
  177. {
  178. memcpy( &pSH->m_PendingBuffer[ sizeof( ProtocolHeader ) ],
  179. & ( ( char *) pData )[ nLinkHeaderLen ],
  180. pHeader->nLen - sizeof( ProtocolHeader ) );
  181. pSH->m_nPendingSize = 0; // 收完所需的包,置m_nPendingSize为0
  182. }
  183. else
  184. {
  185. int nTemp = nLen - nLinkHeaderLen; //除去头剩余部分的长度
  186. if ( nTemp > 0 ) //刚好是Header的长度,不用拷贝内存,所以这里加了>0的判断
  187. {
  188. memcpy( &pSH->m_PendingBuffer[ sizeof( ProtocolHeader ) ],
  189. & ( ( char *) pData )[ nLinkHeaderLen ],
  190. nTemp );
  191. }
  192. pSH->m_nPendingSize += nLen;
  193. }
  194. }
  195. else //这次还是没有收完包头, 继续Pending
  196. {
  197. memcpy( &pSH->m_PendingBuffer[ pSH->m_nPendingSize ], pData, nLen );
  198. pSH->m_nPendingSize += nLen;
  199. nProcessedLen = nLen;
  200. }
  201. }
  202. else //Header部分已经在阻塞的缓冲区中
  203. {
  204. nProcessedLen = pHeader->nLen - pSH->m_nPendingSize;
  205. if ( nProcessedLen <= nLen ) //如果需要处理的长度小于现有包的长度
  206. {
  207. memcpy( &pSH->m_PendingBuffer[ pSH->m_nPendingSize ], pData, nProcessedLen );
  208. pSH->m_nPendingSize = 0;
  209. }
  210. else //否则要继续阻塞
  211. {
  212. memcpy( &pSH->m_PendingBuffer[ pSH->m_nPendingSize ], pData, nLen );
  213. pSH->m_nPendingSize += nLen;
  214. }
  215. }
  216. }
  217. else //第一次接包
  218. {
  219. pHeader = (ProtocolHeader *)&( (unsigned char *)pData )[nBuffIndex];
  220. if( nLen - nBuffIndex < sizeof(ProtocolHeader) ) // 没有收够包头,先记录当前收到的Buffer
  221. {
  222. //如果第一次接包就没有收够包头,认为是非法包,扔掉,就是说已处理的长度nProcessedLen = 0
  223. pSH->m_nPendingSize = nLen - nBuffIndex;
  224. memcpy(pSH->m_PendingBuffer, pHeader, pSH->m_nPendingSize);
  225. }
  226. else
  227. {
  228. nProcessedLen = pHeader->nLen;
  229. if( (int)pHeader->nLen > nLen - nBuffIndex )
  230. {
  231. memcpy(pSH->m_PendingBuffer, pHeader, nLen - nBuffIndex);
  232. //如果第一次接包,pHeader->nLen大于当前包的总长,认为是非法包,扔掉
  233. if( nBuffIndex == 0 )
  234. {
  235. //组包错误,则扔掉当前包
  236. TRACE("pHeader->nLen大于当前包的总长,认为是非法包,扔掉\r\n");
  237. break;
  238. }
  239. pSH->m_nPendingSize = nLen - nBuffIndex;
  240. nProcessedLen = nLen - nBuffIndex;
  241. }
  242. else
  243. {
  244. pSH->m_nPendingSize = 0;
  245. }
  246. }
  247. }
  248. if ( nProcessedLen == 0 )
  249. {
  250. // 没有收够包头,认为是非法包,扔掉
  251. TRACE("没有收够包头,认为是非法包,扔掉\r\n");
  252. break;
  253. }
  254. if ( pSH->m_nPendingSize == 0 )
  255. {
  256. if ( pHeader->nLen > SOCKET_BUFFSIZE )
  257. {
  258. // 包长度超过限制
  259. TRACE("pHeader->nLen超过限制\r\n");
  260. }
  261. if(-1 == OnCmdProcess( pHeader ))
  262. {
  263. //MessageBox( NULL, "Error OnCmdProcess", NULL, MB_OK );
  264. TRACE("crc校验错误!\r\n");
  265. break;
  266. }
  267. }
  268. nBuffIndex += nProcessedLen;
  269. }
  270. LeaveCriticalSection( &(pSH->m_hClient2SrvSection) );
  271. }