IServerImpl.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848
  1. #include "StdAfx.h"
  2. #include "IServerImpl.h"
  3. #include <comdef.h>
  4. #include <atlbase.h>
  5. #include "ThreadPool.hpp"
  6. const int AF_IPV4 = 0;
  7. const int AF_IPV6 = 1;
  8. const int SOCK_TCP = SOCK_STREAM-1;
  9. const int SOCK_UDP = SOCK_DGRAM-1;
  10. namespace ServerSocketImpl
  11. {
  12. IServerImpl* g_pServerSocket[20] = {0};
  13. IServerImpl::IServerImpl():m_nMode(AF_IPV4)
  14. ,m_nSockType(SOCK_TCP)
  15. ,m_strPort(_T("64320"))
  16. ,m_nSocketIndex(0)
  17. {
  18. m_bStopbeat = FALSE;
  19. InitializeCriticalSection( &m_csProcessData );
  20. m_SocketServer.SetInterface(this);
  21. }
  22. IServerImpl::~IServerImpl()
  23. {
  24. m_SocketServer.Terminate();
  25. DeleteCriticalSection( &m_csProcessData );
  26. }
  27. BOOL IServerImpl::Initialize()
  28. {
  29. TCHAR szIPAddr[MAX_PATH] = { 0 };
  30. CSocketHandle::GetLocalAddress(szIPAddr, MAX_PATH, AF_INET);
  31. //AppendText(_T("Local Address (IPv4): %s\r\n"), szIPAddr);
  32. CSocketHandle::GetLocalAddress(szIPAddr, MAX_PATH, AF_INET6);
  33. //AppendText(_T("Local Address (IPv6): %s\r\n"), szIPAddr);
  34. return TRUE;
  35. }
  36. void IServerImpl::Start(IN LPCTSTR strPort,IN const int &nMode)
  37. {
  38. m_nMode = nMode;
  39. int nFamily = (m_nMode == AF_IPV4) ? AF_INET : AF_INET6;
  40. if (!m_SocketServer.StartServer(NULL, strPort, nFamily, (m_nSockType+1)))
  41. {
  42. AfxMessageBox(_T("Failed to start server."), NULL, MB_ICONSTOP);
  43. }
  44. else StartClearInvalidateSocketThread();
  45. //SyncControls();
  46. }
  47. void IServerImpl::Stop()
  48. {
  49. if(m_hRunObject)
  50. SetEvent(m_hRunObject);
  51. if( m_hClearInvalidateSocketThread )
  52. {
  53. if (WaitForSingleObject(m_hClearInvalidateSocketThread,INFINITE) != WAIT_FAILED)
  54. {
  55. CloseHandle(m_hClearInvalidateSocketThread);
  56. m_hClearInvalidateSocketThread = NULL;
  57. }
  58. }
  59. CloseHandle( m_hRunObject );
  60. m_hRunObject = NULL;
  61. m_SocketServer.Terminate();
  62. //SyncControls();
  63. }
  64. void IServerImpl::Send()
  65. {
  66. if ( m_SocketServer.IsOpen() )
  67. {
  68. CString strMsg;
  69. //m_ctlMessage.GetWindowText( strMsg );
  70. if ( strMsg.IsEmpty() )
  71. {
  72. //AppendText( _T("Please enter the message to send.\r\n") );
  73. return;
  74. }
  75. USES_CONVERSION;
  76. if (m_nSockType == SOCK_TCP)
  77. {
  78. const LPBYTE lpbData = (const LPBYTE)(T2CA(strMsg));
  79. // unsafe access to Socket list!
  80. #ifdef SOCKHANDLE_USE_OVERLAPPED
  81. const SocketBufferList& sl = m_SocketServer.GetSocketList();
  82. for(SocketBufferList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  83. #else
  84. const SocketList& sl = m_SocketServer.GetSocketList();
  85. for(SocketList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  86. #endif
  87. {
  88. CSocketHandle sockHandle;
  89. sockHandle.Attach( (*citer) );
  90. sockHandle.Write(lpbData, strMsg.GetLength(), NULL);
  91. sockHandle.Detach();
  92. }
  93. }
  94. else
  95. {
  96. SockAddrIn servAddr, sockAddr;
  97. m_SocketServer->GetSockName(servAddr);
  98. GetDestination(sockAddr);
  99. if ( servAddr != sockAddr )
  100. {
  101. m_SocketServer.Write((const LPBYTE)(T2CA(strMsg)), strMsg.GetLength(), sockAddr);
  102. }
  103. else
  104. {
  105. //AppendText( _T("Please change the port number to send message to a client.\r\n") );
  106. }
  107. }
  108. }
  109. else
  110. {
  111. AfxMessageBox(_T("Socket is not connected"));
  112. }
  113. }
  114. void IServerImpl::SendAll(CSocketHandle &sockHandle, unsigned char *pMsg, int nLength)
  115. {
  116. if ( m_SocketServer.IsOpen() )
  117. {
  118. USES_CONVERSION;
  119. if (m_nSockType == SOCK_TCP)
  120. {
  121. // unsafe access to Socket list!
  122. const LPBYTE lpbData = (const LPBYTE)(pMsg);
  123. sockHandle.Write(lpbData, nLength, NULL);
  124. }
  125. else
  126. {
  127. SockAddrIn servAddr, sockAddr;
  128. m_SocketServer->GetSockName(servAddr);
  129. GetDestination(sockAddr);
  130. if ( servAddr != sockAddr )
  131. {
  132. m_SocketServer.Write((const LPBYTE)*pMsg, nLength, sockAddr);
  133. }
  134. else
  135. {
  136. }
  137. }
  138. }
  139. else
  140. {
  141. }
  142. }
  143. void IServerImpl::ToprocessRecivebuf(IN SocketIOBuffer &sockHandle, IN const BYTE* pReceivebuf, IN DWORD dwReceiveSize)
  144. {
  145. DWORD dwIndexOfProcessed = 0; // 当前接收的包被处理的长度;
  146. DWORD dwOnceProcessedLen = 0; // 循环一次处理了多少当前包;
  147. STProtocolheader *pstProtocolheader;
  148. //LOG4C((LOG_NOTICE,"当前包大小:%d 内容:%s",dwReceiveSize,pReceivebuf));
  149. //LOG4C((LOG_NOTICE,"缓存包大小:%d,内容:%s",sockHandle.npendingSize,sockHandle.szpendingbuf));
  150. while( dwIndexOfProcessed < dwReceiveSize)
  151. {
  152. pstProtocolheader = NULL;
  153. dwOnceProcessedLen = 0;
  154. if ( sockHandle.npendingSize == 0) //----------------------------------------------// 1.第一次接收或完整组包后接收剩余包;
  155. {
  156. //LOG4C((LOG_NOTICE, "1.第一次接收或完整组包后接收剩余包"));
  157. pstProtocolheader = (STProtocolheader *)&((unsigned char *)pReceivebuf)[dwIndexOfProcessed];
  158. if( dwReceiveSize - dwIndexOfProcessed < sizeof(STProtocolheader) ) // 1.1.第一次接收或剩余数据不足一个包头;
  159. {
  160. //LOG4C((LOG_NOTICE, "1.1.第一次接收或剩余数据不足一个包头"));
  161. // 如果第一次接包就没有收够包头,认为是非法包,扔掉,就是说已处理的长度dwOnceProcessedLen = 0;
  162. sockHandle.npendingSize = dwReceiveSize - dwIndexOfProcessed;
  163. memcpy(sockHandle.szpendingbuf, pstProtocolheader, sockHandle.npendingSize);
  164. }
  165. else // 1.2.第一次接收或剩余数据大于一个包头;
  166. {
  167. //LOG4C((LOG_NOTICE, "1.2.第一次接收或剩余数据大于一个包头,协议包长度:%d",pstProtocolheader->nDataLen));
  168. dwOnceProcessedLen = pstProtocolheader->nDataLen;
  169. if( (int)pstProtocolheader->nDataLen > dwReceiveSize - dwIndexOfProcessed ) // 1.2.1.第一次接收或剩余数据不足一个完整的协议包;
  170. {//
  171. //LOG4C((LOG_NOTICE, "1.2.1.第一次接收或剩余数据不足一个完整的协议包"));
  172. memcpy(sockHandle.szpendingbuf, pstProtocolheader, dwReceiveSize - dwIndexOfProcessed);
  173. //如果第一次接包,pstProtocolheader->nDataLen大于当前包的总长,认为是非法包,扔掉(不处理这部分,不一定是非法包)
  174. // if( dwIndexOfProcessed == 0 )
  175. // {
  176. // //组包错误,则扔掉当前包
  177. // LOG4C((LOG_NOTICE, "第一次接包,服务器pstProtocolheader->nDataLen大于当前包的总长,认为是非法包,扔掉"));
  178. // }
  179. sockHandle.npendingSize = dwReceiveSize - dwIndexOfProcessed;
  180. dwOnceProcessedLen = dwReceiveSize - dwIndexOfProcessed; // 该次处理的数据长度;
  181. }
  182. else // ---------------------------------------------------------------------// 1.2.2.第一次接收或剩余数据大于一个完整的协议包;
  183. {
  184. //LOG4C((LOG_NOTICE, "1.2.2.第一次接收或剩余数据大于一个完整的协议包"));
  185. sockHandle.npendingSize = 0;
  186. //memset(sockHandle.szpendingbuf,0,SOCKET_BUFFSIZE);
  187. //dwOnceProcessedLen = pstProtocolheader->nDataLen; // 该次处理的数据长度;
  188. }
  189. }
  190. }
  191. else if( sockHandle.npendingSize > 0) //------------------------------------------------------------------------------// 2.第n+1次接收数据包;
  192. {
  193. pstProtocolheader = (STProtocolheader *)sockHandle.szpendingbuf;
  194. if( sockHandle.npendingSize < sizeof(STProtocolheader) ) // 2.1.pengingbuf数据小于包头
  195. {
  196. //LOG4C((LOG_NOTICE,"2.1.pengingbuf数据小于包头"));
  197. DWORD dwRestheader = sizeof(STProtocolheader) - sockHandle.npendingSize;
  198. if( dwRestheader < dwReceiveSize ) // 2.1.1.当前包大小 > 剩下包头长度,可以组成一个完整包头;
  199. {
  200. //LOG4C((LOG_NOTICE,"2.1.1.当前包大小 > 剩下包头长度,可以组成一个完整包头"));
  201. // -1.先收完一个完整的包头;
  202. memcpy( &sockHandle.szpendingbuf[sockHandle.npendingSize], pReceivebuf, dwRestheader);
  203. //LOG4C((LOG_NOTICE,"2.1.1.当前包大小 > 剩下包头长度,可以组成一个完整包头,协议包长度:%d",pstProtocolheader->nDataLen));
  204. // -2.处理剩余数据;
  205. dwOnceProcessedLen = pstProtocolheader->nDataLen - sockHandle.npendingSize;
  206. if( dwOnceProcessedLen <= dwReceiveSize ) // 2.1.1.1.可以组成一个完整的协议包;
  207. {
  208. //LOG4C((LOG_NOTICE,"2.1.1.1.可以组成一个完整的协议包"));
  209. memcpy( &sockHandle.szpendingbuf[sizeof(STProtocolheader)],
  210. &((char *)pReceivebuf)[dwRestheader],
  211. pstProtocolheader->nDataLen - sizeof(STProtocolheader));
  212. }
  213. else // 2.1.1.2.未能组成一个完整的协议包,断续接收等待;
  214. {
  215. //int nTemp = dwReceiveSize - dwRestheader; //除去头剩余部分的长度
  216. //if ( nTemp > 0 ) //刚好是Header的长度,不用拷贝内存,所以这里加了>0的判断
  217. //{
  218. //memcpy( &pSockHandle->m_szpendingbuf[sizeof(STProtocolheader)],&((char *)pReceivebuf)[dwRestheader],nTemp );
  219. //}
  220. //LOG4C((LOG_NOTICE,"2.1.1.2.未能组成一个完整的协议包,断续接收等待"));
  221. memcpy( &sockHandle.szpendingbuf[sizeof(STProtocolheader)],&((char *)pReceivebuf)[dwRestheader],dwReceiveSize - dwRestheader);
  222. sockHandle.npendingSize += dwReceiveSize;
  223. }
  224. }
  225. else //------------------------------------------------------// 2.1.2.当前包大小 <= 剩下包头长度,未能或刚好组成一个完整的包头;
  226. {
  227. //LOG4C((LOG_NOTICE,"2.1.2.当前包大小 <= 剩下包头长度,未能或刚好组成一个完整的包头"));
  228. memcpy( &sockHandle.szpendingbuf[sockHandle.npendingSize], pReceivebuf, dwReceiveSize );
  229. sockHandle.npendingSize += dwReceiveSize;
  230. dwOnceProcessedLen = dwReceiveSize;
  231. }
  232. }
  233. else // --------------------------------------------------------// 2.2.pengingbuf数据大于包头;
  234. {
  235. dwOnceProcessedLen = pstProtocolheader->nDataLen - sockHandle.npendingSize;
  236. if ( dwOnceProcessedLen <= dwReceiveSize ) // 可以组成一个完整的协议包;
  237. {
  238. //LOG4C((LOG_NOTICE,"2.2.1.可以组成一个完整的协议包"));
  239. memcpy( &sockHandle.szpendingbuf[sockHandle.npendingSize], pReceivebuf, dwOnceProcessedLen );
  240. sockHandle.npendingSize = 0;
  241. //memset(sockHandle.szpendingbuf,0,SOCKET_BUFFSIZE);
  242. }
  243. else // 未能组成一个完整协议包;
  244. {
  245. //LOG4C((LOG_NOTICE,"2.2.2.未能组成一个完整协议包"));
  246. memcpy( &sockHandle.szpendingbuf[sockHandle.npendingSize], pReceivebuf, dwReceiveSize );
  247. sockHandle.npendingSize += dwReceiveSize;
  248. }
  249. }
  250. }
  251. //LOG4C((LOG_NOTICE,"*********%d,%s",sockHandle.npendingSize,sockHandle.szpendingbuf));
  252. if ( dwOnceProcessedLen == 0 )
  253. {
  254. // 没有收够包头,认为是非法包,扔掉
  255. LOG4C((LOG_NOTICE, "*****没有收够包头,认为是非法包,扔掉"));
  256. break;
  257. }
  258. if ( sockHandle.npendingSize == 0 )
  259. {
  260. //LOG4C((LOG_NOTICE, "ok.处理完整协议包的解析工作"));
  261. if ( pstProtocolheader->nDataLen > SOCKET_BUFFSIZE )
  262. {
  263. // 包长度超过限制,暂时不处理;
  264. LOG4C((LOG_NOTICE, "pstProtocolheader->nDataLen超过限制"));
  265. }
  266. if(-1 == OnIntegrityPacket(sockHandle, pstProtocolheader))
  267. {
  268. LOG4C((LOG_NOTICE, "Error OnIntegrityPacket"));
  269. break;
  270. }
  271. }
  272. //LOG4C((LOG_NOTICE,"//////////%d,%s",sockHandle.npendingSize,sockHandle.szpendingbuf));
  273. dwIndexOfProcessed += dwOnceProcessedLen;
  274. }
  275. }
  276. int IServerImpl::OnIntegrityPacket(IN SocketIOBuffer &sockHandle, IN void *pIntegrityPacket)
  277. {
  278. STProtocolheader *pHeader = (STProtocolheader *)pIntegrityPacket;
  279. if( pHeader == NULL )
  280. {
  281. LOG4C((LOG_NOTICE,"pHeader == NULL"));
  282. return -1;
  283. }
  284. if( pHeader->bof != PBOF)
  285. {
  286. LOG4C((LOG_NOTICE,"协议头标识错误"));
  287. return -1;
  288. }
  289. //if( pHeader->nDataLen < 0 || pHeader->nDataLen > 65535 )
  290. if( pHeader->nDataLen < 0 || pHeader->nDataLen > 1024*1024 )
  291. {
  292. LOG4C((LOG_NOTICE,"协议长度越界错误"));
  293. return -1;
  294. }
  295. unsigned int tmp = VerifyIntegrityPacket(pHeader, pHeader->nDataLen);
  296. //LOG4C((LOG_NOTICE,"协议标识:%d,协议命令:%d,协议类型:%d,协议长度:%d,协议校验:%d",pHeader->bof,pHeader->nCmd,pHeader->nCmdType,pHeader->nDataLen,pHeader->nVerify));
  297. //unsigned char *pBody = &((unsigned char*)pIntegrityPacket)[sizeof(STProtocolheader)];
  298. //LOG4C((LOG_NOTICE,"内容:%s",pBody));
  299. if(tmp != pHeader->nVerify)
  300. {
  301. LOG4C((LOG_NOTICE,"协议校验值错误:len=%d,%d != %d",pHeader->nDataLen,tmp,pHeader->nVerify));
  302. return -1;
  303. }
  304. switch (pHeader->nCmd)
  305. {
  306. case CMD_HEART: // 公共命令:心跳包
  307. {
  308. // 心跳包,不处理任务事务;
  309. //LOG4C((LOG_NOTICE,"接收到的心跳包"));
  310. }
  311. break;
  312. case CMD_TOCHAT: // 公共命令:文字聊天;
  313. {
  314. STChatbody *tChatbody = (STChatbody*)pIntegrityPacket;
  315. //TRACE("------------------");
  316. //AfxMessageBox(tChatbody->szChat);
  317. //LOG4C((LOG_NOTICE,"聊天内容:%s",tChatbody->szChat));
  318. }
  319. break;
  320. case CMD_FILEINFO_TRANSFER: // 公共命令:文件传输;
  321. {
  322. //LOG4C((LOG_NOTICE,"文件信息传输"));
  323. // 需要向客户端返回本地文件的信息:
  324. // 1.若不存在指定文件名,则返回FileSeek = 0;(文件位置指针)
  325. // 2.若文件存在,则读取文件大小,如果文件大小 == 客户端文件大小,表示已有完整文件,不进行传输;
  326. // 3.若文件存在,但文件大小 < 客户端文件大小,认为没有传守文件,继传。
  327. // 4.若文件存在,但文件大小 > 客户端文件大小,先删除本地文件,再与1相同处理。
  328. // 服务端要维护一个文件列表,用于记录客户端需要传输的文件;
  329. // 客户端同样维护一个文件列表,用于记录要传输的文件;
  330. // 两边文件列表一致;
  331. g_dwRecived = 0;
  332. if ( g_pSTFileInfobody == NULL )
  333. {
  334. g_pSTFileInfobody = new STFileInfobody();
  335. }
  336. memset(g_pSTFileInfobody,0,sizeof(STFileInfobody));
  337. memcpy(g_pSTFileInfobody,pIntegrityPacket,sizeof(STFileInfobody));
  338. //g_pSTFileInfobody = (STFileInfobody*)pIntegrityPacket;
  339. LOG4C((LOG_NOTICE,"%d:%d:%d:%d:%d, %s:%d:%d:%d",
  340. g_pSTFileInfobody->tPHeader.bof,
  341. g_pSTFileInfobody->tPHeader.nCmd,
  342. g_pSTFileInfobody->tPHeader.nCmdType,
  343. g_pSTFileInfobody->tPHeader.nDataLen,
  344. g_pSTFileInfobody->tPHeader.nVerify,
  345. g_pSTFileInfobody->szFileName,
  346. g_pSTFileInfobody->nFileLength,
  347. g_pSTFileInfobody->tCreateDate,
  348. g_pSTFileInfobody->tModifyDate));
  349. TCHAR szFileFullName[MAX_PATH] = _T("");
  350. sprintf(szFileFullName,"%s\%s",g_ModulePath,g_pSTFileInfobody->szFileName);
  351. memcpy(g_pSTFileInfobody->szFileName,szFileFullName,MAX_PATH);
  352. LOG4C((LOG_NOTICE,"文件名:%s",g_pSTFileInfobody->szFileName));
  353. }
  354. break;
  355. case CMD_FILECONT_TRANSFER:
  356. {
  357. //LOG4C((LOG_NOTICE,"文件内容传输"));
  358. // 文件传输需要单独出一个端口来独立完成,且只接收客户端排队文件传输。
  359. if ( g_pSTFileInfobody == NULL )
  360. {
  361. LOG4C((LOG_NOTICE,"接收文件信息失败"));
  362. return 0;
  363. }
  364. CFile file;
  365. CFileException e;
  366. file.Open(g_pSTFileInfobody->szFileName, CFile::modeNoTruncate|CFile::modeWrite|CFile::modeCreate|CFile::shareExclusive, &e);
  367. if (e.m_cause != 0)
  368. {
  369. DWORD dw = GetLastError();
  370. LOG4C((LOG_NOTICE,"创建或打开文件失败:%d",dw)); // dw = 53,表示写文件的速度还不及收的速度快。上次未写完,这次又要开始打开文件写.
  371. file.Close();
  372. return -1;
  373. }
  374. STFileContextbody *pFileContextbody = (STFileContextbody*)pIntegrityPacket;
  375. //__int64 nTotal = 0;
  376. //while( g_dwRecived < g_STFileInfobody.nFileLength )
  377. //{
  378. file.SeekToEnd();
  379. file.Write(pFileContextbody->szFileContext, pFileContextbody->nFileContextLen);
  380. g_dwRecived += pHeader->nDataLen;
  381. //}
  382. file.Close();
  383. //CFile::SetStatus(xInfo.szFileName,xInfo.fStat);
  384. }
  385. break;
  386. case C2LCMD_REQ_LOGIN:
  387. {
  388. // 1.判断登录信息(加密狗信息);
  389. // 2.信息从数据库中获取,比对正常允许通信;
  390. // **3.若信息比对失败,断开连接;
  391. // 3.若信息比对失败,允许连接,但不返回数据库信息;
  392. // 本端可对其进行控制。
  393. }
  394. break;
  395. case C2CCMD_REQ_LOGIN:
  396. {
  397. // 1.判断登录信息(账号+密码);
  398. // 2.信息从数据库中获取,比对正常允许通信,并返回数据库信息;
  399. // 3.若信息比对失败,断开连接;
  400. STAccountInfobody *tAccountInfobody = (STAccountInfobody*)pIntegrityPacket;
  401. if ( (strcmp(tAccountInfobody->szAccount,"admin") == 0) && (strcmp(tAccountInfobody->szPassword,"admin123456") == 0) )
  402. {
  403. TRACE("账号信息完全匹配");
  404. LOG4C((LOG_NOTICE,"账号信息完全匹配"));
  405. // 临时步骤,数据库信息应该做为全局变量保存; g_STDatabaseInfobody;
  406. STDatabaseInfobody tDatabaseInfobody;
  407. // ....配置好数据库信息;
  408. // ....................
  409. strcpy(tDatabaseInfobody.szDatabaseServer,"127.0.0.1");
  410. strcpy(tDatabaseInfobody.szDatabaseTCPPort,"1433");
  411. strcpy(tDatabaseInfobody.szDatabaseAccount,"sa");
  412. strcpy(tDatabaseInfobody.szDatabasePassword,"ly1234");
  413. strcpy(tDatabaseInfobody.szDatabaseName,"db");
  414. tDatabaseInfobody.GetVerify();
  415. //m_SocketServer->Write();
  416. CSocketHandle tSockhandle;
  417. tSockhandle.Attach(sockHandle);
  418. m_bStopbeat = TRUE;//停止心跳包;
  419. if( -1 == tSockhandle.Write((const LPBYTE)(&tDatabaseInfobody), tDatabaseInfobody.tPHeader.nDataLen, NULL))
  420. {
  421. // 发送失败;
  422. LOG4C((LOG_NOTICE,"发送失败ooo"));
  423. tSockhandle.Detach();
  424. }
  425. tSockhandle.Detach();
  426. m_bStopbeat = FALSE;//恢复心跳包;
  427. }
  428. else
  429. {
  430. TRACE("账号或密码错误");
  431. LOG4C((LOG_NOTICE,"账号或密码错误,关闭该套接字,拒绝连接"));
  432. // 关闭该套接字,拒绝连接;
  433. CSocketHandle::ShutdownConnection(sockHandle);
  434. }
  435. }
  436. break;
  437. default: return 0;
  438. }
  439. memset(sockHandle.szpendingbuf,0,SOCKET_BUFFSIZE);
  440. return 0;
  441. }
  442. // unsigned int IServerImpl::VerityIntegrityPacket(IN void *pIntegrityPacket,unsigned int nPacketSize)
  443. // {
  444. // unsigned int checksum = 0;
  445. // unsigned char *pBody = &((unsigned char*)pIntegrityPacket)[sizeof(STProtocolheader)];
  446. //
  447. // if( pBody )
  448. // checksum = crc32( 0, pBody, nPacketSize );
  449. //
  450. // return checksum;
  451. // }
  452. void IServerImpl::GetAddress(const SockAddrIn& addrIn, CString& rString) const
  453. {
  454. TCHAR szIPAddr[MAX_PATH] = { 0 };
  455. CSocketHandle::FormatIP(szIPAddr, MAX_PATH, addrIn);
  456. rString.Format(_T("%s : %d"), szIPAddr, static_cast<int>(static_cast<UINT>(ntohs(addrIn.GetPort()))) );
  457. }
  458. void IServerImpl::AppendText(LPCTSTR lpszFormat, ...)
  459. {
  460. // if ( !::IsWindow(m_ctlMsgList.GetSafeHwnd()) ) return;
  461. // TCHAR szBuffer[512];
  462. // HWND hWnd = m_ctlMsgList.GetSafeHwnd();
  463. // DWORD dwResult = 0;
  464. // if (SendMessageTimeout(hWnd, WM_GETTEXTLENGTH, 0, 0, SMTO_NORMAL, 500L, &dwResult) != 0)
  465. // {
  466. // int nLen = (int) dwResult;
  467. // if (SendMessageTimeout(hWnd, EM_SETSEL, nLen, nLen, SMTO_NORMAL, 500L, &dwResult) != 0)
  468. // {
  469. // size_t cb = 0;
  470. // va_list args;
  471. // va_start(args, lpszFormat);
  472. // ::StringCchVPrintfEx(szBuffer, 512, NULL, &cb, 0, lpszFormat, args);
  473. // va_end(args);
  474. // SendMessageTimeout(hWnd, EM_REPLACESEL, FALSE, reinterpret_cast<LPARAM>(szBuffer), SMTO_NORMAL, 500L, &dwResult);
  475. // }
  476. // }
  477. }
  478. bool IServerImpl::GetDestination(SockAddrIn& addrIn) const
  479. {
  480. CString strPort;
  481. //GetDlgItemText(IDC_SVR_PORT, strPort);
  482. int nFamily = (m_nMode == AF_IPV4) ? AF_INET : AF_INET6;
  483. return addrIn.CreateFrom(NULL, strPort, nFamily);
  484. }
  485. bool IServerImpl::SetupMCAST()
  486. {
  487. const TCHAR szIPv4MCAST[] = TEXT("239.121.1.2");
  488. const TCHAR szIPv6MCAST[] = TEXT("FF02:0:0:0:0:0:0:1"); // All Nodes local address
  489. bool result = false;
  490. if ( m_nSockType == SOCK_UDP )
  491. {
  492. if ( m_nMode == AF_IPV4 ) {
  493. result = m_SocketServer->AddMembership(szIPv4MCAST, NULL);
  494. } else {
  495. result = m_SocketServer->AddMembership(szIPv6MCAST, NULL);
  496. HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  497. hr = hr;
  498. }
  499. }
  500. return result;
  501. }
  502. ///////////////////////////////////////////////////////////////////////////////
  503. void IServerImpl::OnThreadBegin(CSocketHandle* pSH)
  504. {
  505. ASSERT( pSH == m_SocketServer );
  506. (pSH);
  507. CString strAddr;
  508. SockAddrIn sockAddr;
  509. m_SocketServer->GetSockName(sockAddr);
  510. GetAddress( sockAddr, strAddr );
  511. //AppendText( _T("Server Running on: %s\r\n"), strAddr);
  512. }
  513. void IServerImpl::OnThreadExit(CSocketHandle* pSH)
  514. {
  515. ASSERT( pSH == m_SocketServer );
  516. (pSH);
  517. //AppendText( _T("Server Down!\r\n"));
  518. }
  519. void IServerImpl::OnConnectionFailure(CSocketHandle* pSH, SOCKET newSocket)
  520. {
  521. ASSERT( pSH == m_SocketServer );
  522. (pSH);
  523. CString strAddr;
  524. CSocketHandle sockHandle;
  525. SockAddrIn sockAddr;
  526. if (newSocket != INVALID_SOCKET)
  527. {
  528. sockHandle.Attach( newSocket );
  529. sockHandle.GetPeerName( sockAddr );
  530. GetAddress( sockAddr, strAddr );
  531. sockHandle.Close();
  532. //AppendText( _T("Connection abandoned: %s\r\n"), strAddr );
  533. LOG4C((LOG_NOTICE,"Connection abandoned:%s",strAddr));
  534. }
  535. else
  536. {
  537. //AppendText( _T("Connection abandoned. Not a valid socket.\r\n"), strAddr );
  538. LOG4C((LOG_NOTICE,"Connection abandoned. Not a valid socket:%s",strAddr));
  539. }
  540. }
  541. void IServerImpl::OnAddConnection(CSocketHandle* pSH, SOCKET newSocket)
  542. {
  543. ASSERT( pSH == m_SocketServer );
  544. (pSH);
  545. CString strAddr;
  546. CSocketHandle sockHandle;
  547. SockAddrIn sockAddr;
  548. sockHandle.Attach( newSocket );
  549. sockHandle.GetPeerName( sockAddr );
  550. GetAddress( sockAddr, strAddr );
  551. sockHandle.Detach();
  552. //LOG4C((LOG_NOTICE,"新的连接接入:%s",strAddr));
  553. //AppendText( _T("Connection established: %s\r\n"), strAddr );
  554. }
  555. // void IServerImpl::OnDataReceived(CSocketHandle* pSH, const BYTE* pbData, DWORD dwCount, const SockAddrIn& addr)
  556. // {
  557. // ASSERT( pSH == m_SocketServer );
  558. // (pSH);
  559. // CString strAddr, strText;
  560. // USES_CONVERSION;
  561. // LPTSTR pszText = strText.GetBuffer(dwCount+1);
  562. // ::StringCchCopyN(pszText, dwCount+1, A2CT(reinterpret_cast<LPCSTR>(pbData)), dwCount);
  563. // strText.ReleaseBuffer();
  564. // GetAddress( addr, strAddr );
  565. // AppendText( _T("%s>(%s)\r\n"), strAddr, strText);
  566. //
  567. // if (m_nSockType == SOCK_TCP)
  568. // {
  569. // // unsafe access to Socket list!
  570. //#ifdef SOCKHANDLE_USE_OVERLAPPED
  571. // const SocketBufferList& sl = m_SocketServer.GetSocketList();
  572. // for(SocketBufferList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  573. //#else
  574. // const SocketList& sl = m_SocketServer.GetSocketList();
  575. // for(SocketList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  576. //#endif
  577. // {
  578. // EnterCriticalSection( &m_csProcessData );
  579. //#if 0
  580. // CSocketHandle sockHandle;
  581. // sockHandle.m_npendingSize = 0;
  582. // memset(sockHandle.m_szpendingbuf, 0, SOCKET_BUFFSIZE);
  583. // sockHandle.Attach( (*citer) );
  584. // SockAddrIn sockAddr;
  585. // sockHandle.GetPeerName(sockAddr);
  586. // if( sockAddr == addr )
  587. // {
  588. // ToprocessRecivebuf(sockHandle,pbData,dwCount);
  589. // }
  590. // sockHandle.Detach();
  591. //#else
  592. // if ( addr == SockAddrIn(*citer))
  593. // {
  594. // ToprocessRecivebuf(*citer,pbData,dwCount);
  595. // }
  596. //#endif
  597. // LeaveCriticalSection( &m_csProcessData );
  598. // }
  599. // }
  600. // else
  601. // {
  602. // SockAddrIn servAddr, sockAddr;
  603. // m_SocketServer->GetSockName(servAddr);
  604. // GetDestination(sockAddr);
  605. // if ( servAddr != sockAddr )
  606. // {
  607. // //m_SocketServer.Write((const LPBYTE)(T2CA(strMsg)), strMsg.GetLength(), sockAddr);
  608. // } else
  609. // {
  610. // //AppendText( _T("Please change the port number to send message to a client.\r\n") );
  611. // }
  612. // }
  613. // }
  614. void IServerImpl::OnDataReceived(CSocketHandle* pSH, const BYTE* pbData, DWORD dwCount, const SockAddrIn& addr)
  615. {
  616. ASSERT( pSH == m_SocketServer );
  617. (pSH);
  618. CString strAddr, strText;
  619. USES_CONVERSION;
  620. LPTSTR pszText = strText.GetBuffer(dwCount+1);
  621. ::StringCchCopyN(pszText, dwCount+1, A2CT(reinterpret_cast<LPCSTR>(pbData)), dwCount);
  622. strText.ReleaseBuffer();
  623. GetAddress( addr, strAddr );
  624. AppendText( _T("%s>(%s)\r\n"), strAddr, strText);
  625. if (m_nSockType == SOCK_TCP)
  626. {
  627. // unsafe access to Socket list!
  628. #ifdef SOCKHANDLE_USE_OVERLAPPED
  629. const SocketBufferList& sl = m_SocketServer.GetSocketList();
  630. for(SocketBufferList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  631. #else
  632. const SocketList& sl = m_SocketServer.GetSocketList();
  633. for(SocketList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  634. #endif
  635. {
  636. EnterCriticalSection( &m_csProcessData );
  637. if ( addr == SockAddrIn(*citer))
  638. {
  639. ToprocessRecivebuf((SocketIOBuffer&)*citer,pbData,dwCount);
  640. }
  641. LeaveCriticalSection( &m_csProcessData );
  642. }
  643. }
  644. else
  645. {
  646. SockAddrIn servAddr, sockAddr;
  647. m_SocketServer->GetSockName(servAddr);
  648. GetDestination(sockAddr);
  649. if ( servAddr != sockAddr )
  650. {
  651. //m_SocketServer.Write((const LPBYTE)(T2CA(strMsg)), strMsg.GetLength(), sockAddr);
  652. } else
  653. {
  654. //AppendText( _T("Please change the port number to send message to a client.\r\n") );
  655. }
  656. }
  657. }
  658. void IServerImpl::OnConnectionDropped(CSocketHandle* pSH)
  659. {
  660. ASSERT( pSH == m_SocketServer );
  661. (pSH);
  662. //AppendText( _T("Connection lost with client.\r\n") );
  663. LOG4C((LOG_NOTICE,"Connection lost with client"));
  664. }
  665. void IServerImpl::OnConnectionError(CSocketHandle* pSH, DWORD dwError)
  666. {
  667. ASSERT( pSH == m_SocketServer );
  668. (pSH);
  669. _com_error err(dwError);
  670. //AppendText( _T("Communication Error:\r\n%s\r\n"), err.ErrorMessage() );
  671. LOG4C((LOG_NOTICE,"Communication Error:%s",err.ErrorMessage()));
  672. }
  673. #if defined(SOCKHANDLE_USE_OVERLAPPED)
  674. void IServerImpl::OnRemoveConnection(CSocketHandle* pSH, SOCKET dropSocket)
  675. {
  676. return ;
  677. ASSERT( pSH == m_SocketServer );
  678. (pSH);
  679. CString strAddr;
  680. CSocketHandle sockHandle;
  681. SockAddrIn sockAddr;
  682. sockHandle.Attach( dropSocket );
  683. sockHandle.GetPeerName( sockAddr );
  684. GetAddress( sockAddr, strAddr );
  685. sockHandle.Detach();
  686. LOG4C((LOG_NOTICE,"删除无效连接:%s",strAddr));
  687. }
  688. #endif
  689. DWORD IServerImpl::GetClientConnectCount()
  690. {
  691. //DWORD dwClientSize = 0;
  692. //m_SocketServer->GetConnectionCount();
  693. return m_SocketServer.GetConnectionCount();
  694. }
  695. void IServerImpl::StartClearInvalidateSocketThread()
  696. {
  697. m_hRunObject = CreateEvent( NULL, TRUE, FALSE, "ClearInvalidateSocketThread" );
  698. if ( m_hRunObject == NULL )
  699. {
  700. LOG4C((LOG_NOTICE,"创建事件失败"));
  701. }
  702. m_hClearInvalidateSocketThread = CreateThread(NULL,0,ClearInvalidateSocketThread,this,0,NULL);
  703. if ( m_hClearInvalidateSocketThread == NULL )
  704. {
  705. LOG4C((LOG_NOTICE,"创建线程失败"));
  706. }
  707. }
  708. DWORD WINAPI IServerImpl::ClearInvalidateSocketThread(void *pInstance)
  709. {
  710. LOG4C((LOG_NOTICE,"服务端心跳检测线程"));
  711. IServerImpl *pServerImpl = (IServerImpl*)pInstance;
  712. #ifdef SOCKHANDLE_USE_OVERLAPPED
  713. /*const*/ SocketBufferList& sl = pServerImpl->m_SocketServer.GetClientSocketList();
  714. SocketBufferList::const_iterator citer = sl.begin();
  715. #else
  716. /*const*/ SocketList& sl = pServerImpl->m_SocketServer.GetClientSocketList();
  717. SocketList::const_iterator citer = sl.begin();
  718. #endif
  719. #if 0
  720. STProtocolheader tProtocolheader;
  721. tProtocolheader.nVerify = VerityIntegrityPacket(&tProtocolheader, sizeof(STProtocolheader));
  722. #else
  723. STChatbody tChatbody;
  724. memset(tChatbody.szChat,97,MAX_CHATLENGTH);
  725. //tChatbody.tPHeader.nVerify = VerifyIntegrityPacket(&tChatbody, sizeof(STChatbody));
  726. tChatbody.GetVerify();
  727. #endif
  728. //SockAddrIn sockAddr;
  729. //size_t nSize = sl.size();
  730. CSocketHandle tSocketHandle;
  731. do
  732. {
  733. //nSize = sl.size();
  734. if ( !pServerImpl->m_bStopbeat )
  735. {
  736. //AutoThreadSection aSenction(pServerImpl->m_SocketServer.ReturnSection());
  737. //if( (nSize != 0) && (citer != sl.end()))
  738. if ( citer != sl.end())
  739. {
  740. tSocketHandle.Attach( (*citer) );
  741. //if( -1 == tSocketHandle.Write((const LPBYTE)(&tProtocolheader), tProtocolheader.nDataLen, sockAddr))
  742. //if( -1 == tSocketHandle.Write((const LPBYTE)(&tProtocolheader), tProtocolheader.nDataLen, NULL))
  743. if( -1 == tSocketHandle.Write((const LPBYTE)(&tChatbody), tChatbody.tPHeader.nDataLen, NULL))
  744. {
  745. CString strAddr;
  746. SockAddrIn sockAddr = SockAddrIn(*citer);
  747. pServerImpl->GetAddress( sockAddr, strAddr );
  748. tSocketHandle.Close();
  749. citer = sl.erase(citer);
  750. tSocketHandle.Detach();
  751. LOG4C((LOG_NOTICE,"服务端成功删除无效SOCKET:%s",strAddr));
  752. continue;
  753. }
  754. else
  755. {
  756. citer++;
  757. }
  758. tSocketHandle.Detach();
  759. }
  760. else if ( citer == sl.end() )
  761. {
  762. citer = sl.begin();
  763. }
  764. }
  765. } while (WaitForSingleObject(pServerImpl->m_hRunObject,10L) == WAIT_TIMEOUT);
  766. return 0;
  767. }
  768. };