IServerImpl.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. //SyncControls();
  45. }
  46. void IServerImpl::Stop()
  47. {
  48. m_SocketServer.Terminate();
  49. //SyncControls();
  50. }
  51. void IServerImpl::Send()
  52. {
  53. if ( m_SocketServer.IsOpen() )
  54. {
  55. CString strMsg;
  56. //m_ctlMessage.GetWindowText( strMsg );
  57. if ( strMsg.IsEmpty() )
  58. {
  59. //AppendText( _T("Please enter the message to send.\r\n") );
  60. return;
  61. }
  62. USES_CONVERSION;
  63. if (m_nSockType == SOCK_TCP)
  64. {
  65. const LPBYTE lpbData = (const LPBYTE)(T2CA(strMsg));
  66. // unsafe access to Socket list!
  67. #ifdef SOCKHANDLE_USE_OVERLAPPED
  68. const SocketBufferList& sl = m_SocketServer.GetSocketList();
  69. for(SocketBufferList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  70. #else
  71. const SocketList& sl = m_SocketServer.GetSocketList();
  72. for(SocketList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  73. #endif
  74. {
  75. CSocketHandle sockHandle;
  76. sockHandle.Attach( (*citer) );
  77. sockHandle.Write(lpbData, strMsg.GetLength(), NULL);
  78. sockHandle.Detach();
  79. }
  80. }
  81. else
  82. {
  83. SockAddrIn servAddr, sockAddr;
  84. m_SocketServer->GetSockName(servAddr);
  85. GetDestination(sockAddr);
  86. if ( servAddr != sockAddr )
  87. {
  88. m_SocketServer.Write((const LPBYTE)(T2CA(strMsg)), strMsg.GetLength(), sockAddr);
  89. }
  90. else
  91. {
  92. //AppendText( _T("Please change the port number to send message to a client.\r\n") );
  93. }
  94. }
  95. }
  96. else
  97. {
  98. AfxMessageBox(_T("Socket is not connected"));
  99. }
  100. }
  101. void IServerImpl::SendAll(CSocketHandle &sockHandle, unsigned char *pMsg, int nLength)
  102. {
  103. if ( m_SocketServer.IsOpen() )
  104. {
  105. USES_CONVERSION;
  106. if (m_nSockType == SOCK_TCP)
  107. {
  108. // unsafe access to Socket list!
  109. const LPBYTE lpbData = (const LPBYTE)(pMsg);
  110. sockHandle.Write(lpbData, nLength, NULL);
  111. }
  112. else
  113. {
  114. SockAddrIn servAddr, sockAddr;
  115. m_SocketServer->GetSockName(servAddr);
  116. GetDestination(sockAddr);
  117. if ( servAddr != sockAddr )
  118. {
  119. m_SocketServer.Write((const LPBYTE)*pMsg, nLength, sockAddr);
  120. }
  121. else
  122. {
  123. }
  124. }
  125. }
  126. else
  127. {
  128. }
  129. }
  130. void IServerImpl::ToprocessRecivebuf(IN SocketIOBuffer &sockHandle, IN const BYTE* pReceivebuf, IN DWORD dwReceiveSize)
  131. {
  132. // 当前接收的包被处理的长度;
  133. DWORD dwIndexOfProcessed = 0;
  134. // 循环一次处理了多少当前包;
  135. DWORD dwOnceProcessedLen = 0;
  136. STProtocolheader *pstProtocolheader;
  137. while( dwIndexOfProcessed < dwReceiveSize)
  138. {
  139. pstProtocolheader = NULL;
  140. dwOnceProcessedLen = 0;
  141. // 1.第一次接收或完整组包后接收剩余包;
  142. if ( sockHandle.npendingSize == 0)
  143. {
  144. // 1.1.第一次接收或剩余数据不足一个包头;
  145. if( dwReceiveSize - dwIndexOfProcessed < sizeof(STProtocolheader) )
  146. {
  147. sockHandle.npendingSize = dwReceiveSize - dwIndexOfProcessed;
  148. memcpy(sockHandle.szpendingbuf, &pReceivebuf[dwIndexOfProcessed], sockHandle.npendingSize);
  149. dwOnceProcessedLen = dwReceiveSize - dwIndexOfProcessed;
  150. }
  151. // 1.2.第一次接收或剩余数据大于一个包头;
  152. else
  153. {
  154. pstProtocolheader = (STProtocolheader *)&((unsigned char *)pReceivebuf)[dwIndexOfProcessed];
  155. // 1.2.1.第一次接收或剩余数据不足一个完整的协议包;
  156. if( (int)pstProtocolheader->nDataLen > dwReceiveSize - dwIndexOfProcessed )
  157. {
  158. memcpy(sockHandle.szpendingbuf, &pReceivebuf[dwIndexOfProcessed], dwReceiveSize - dwIndexOfProcessed);
  159. sockHandle.npendingSize = dwReceiveSize - dwIndexOfProcessed;
  160. // 该次处理的数据长度;
  161. dwOnceProcessedLen = dwReceiveSize - dwIndexOfProcessed;
  162. }
  163. // 1.2.2.第一次接收或剩余数据大于一个完整的协议包;
  164. else
  165. {
  166. sockHandle.npendingSize = 0;
  167. // 该次处理的数据长度;
  168. dwOnceProcessedLen = pstProtocolheader->nDataLen;
  169. }
  170. }
  171. }
  172. // 2.第n+1次接收数据包;
  173. else if( sockHandle.npendingSize > 0)
  174. {
  175. // 2.1.pengingbuf数据小于包头
  176. if( sockHandle.npendingSize < sizeof(STProtocolheader) )
  177. {
  178. DWORD dwRestheader = sizeof(STProtocolheader) - sockHandle.npendingSize;
  179. // 2.1.1.当前包大小 > 剩下包头长度,可以组成一个完整包头;
  180. if( dwRestheader < dwReceiveSize )
  181. {
  182. // -1.先收完一个完整的包头;
  183. memcpy( &sockHandle.szpendingbuf[sockHandle.npendingSize], pReceivebuf, dwRestheader);
  184. // -2.处理剩余数据;
  185. pstProtocolheader = (STProtocolheader *)sockHandle.szpendingbuf;
  186. dwOnceProcessedLen = pstProtocolheader->nDataLen - sockHandle.npendingSize;
  187. // 2.1.1.1.可以组成一个完整的协议包;
  188. if( dwOnceProcessedLen <= dwReceiveSize )
  189. {
  190. memcpy( &sockHandle.szpendingbuf[sizeof(STProtocolheader)],
  191. &((char *)pReceivebuf)[dwRestheader],
  192. pstProtocolheader->nDataLen - sizeof(STProtocolheader));
  193. sockHandle.npendingSize = 0;
  194. }
  195. // 2.1.1.2.未能组成一个完整的协议包,断续接收等待;
  196. else
  197. {
  198. memcpy( &sockHandle.szpendingbuf[sizeof(STProtocolheader)],&((char *)pReceivebuf)[dwRestheader],dwReceiveSize - dwRestheader);
  199. sockHandle.npendingSize += dwReceiveSize;
  200. }
  201. }
  202. // 2.1.2.当前包大小 <= 剩下包头长度,未能或刚好组成一个完整的包头;
  203. else
  204. {
  205. memcpy( &sockHandle.szpendingbuf[sockHandle.npendingSize], pReceivebuf, dwReceiveSize );
  206. sockHandle.npendingSize += dwReceiveSize;
  207. dwOnceProcessedLen = dwReceiveSize;
  208. }
  209. }
  210. // 2.2.pengingbuf数据大于包头;
  211. else
  212. {
  213. pstProtocolheader = (STProtocolheader *)sockHandle.szpendingbuf;
  214. dwOnceProcessedLen = pstProtocolheader->nDataLen - sockHandle.npendingSize;
  215. // 2.2.1.可以组成一个完整的协议包;
  216. if ( dwOnceProcessedLen <= dwReceiveSize )
  217. {
  218. memcpy( &sockHandle.szpendingbuf[sockHandle.npendingSize], pReceivebuf, dwOnceProcessedLen );
  219. sockHandle.npendingSize = 0;
  220. }
  221. // 2.2.2.未能组成一个完整协议包;
  222. else
  223. {
  224. memcpy( &sockHandle.szpendingbuf[sockHandle.npendingSize], pReceivebuf, dwReceiveSize );
  225. sockHandle.npendingSize += dwReceiveSize;
  226. }
  227. }
  228. }
  229. if ( dwOnceProcessedLen == 0 )
  230. {
  231. // 没有收够包头,认为是非法包,扔掉
  232. LOG4C((LOG_NOTICE, "*****没有收够包头,认为是非法包,扔掉"));
  233. break;
  234. }
  235. if ( sockHandle.npendingSize == 0 )
  236. {
  237. //LOG4C((LOG_NOTICE, "ok.处理完整协议包的解析工作"));
  238. if ( pstProtocolheader->nDataLen > SOCKET_BUFFSIZE )
  239. {
  240. // 包长度超过限制,暂时不处理;
  241. LOG4C((LOG_NOTICE, "pstProtocolheader->nDataLen超过限制"));
  242. }
  243. if(-1 == OnIntegrityPacket(sockHandle, pstProtocolheader))
  244. {
  245. LOG4C((LOG_NOTICE, "Error OnIntegrityPacket"));
  246. memset(sockHandle.szpendingbuf,0,sockHandle.npendingSize);
  247. sockHandle.npendingSize = 0;
  248. break;
  249. }
  250. }
  251. dwIndexOfProcessed += dwOnceProcessedLen;
  252. }
  253. }
  254. int IServerImpl::OnIntegrityPacket(IN SocketIOBuffer &sockHandle, IN void *pIntegrityPacket)
  255. {
  256. STProtocolheader *pHeader = (STProtocolheader *)pIntegrityPacket;
  257. if( pHeader == NULL )
  258. {
  259. LOG4C((LOG_NOTICE,"pHeader == NULL"));
  260. return -1;
  261. }
  262. if( pHeader->bof != PBOF)
  263. {
  264. LOG4C((LOG_NOTICE,"协议头标识错误"));
  265. return -1;
  266. }
  267. //if( pHeader->nDataLen < 0 || pHeader->nDataLen > 65535 )
  268. if( pHeader->nDataLen > 1024*1024 )
  269. {
  270. LOG4C((LOG_NOTICE,"协议长度越界错误"));
  271. return -1;
  272. }
  273. unsigned int tmp = VerifyIntegrityPacket(pHeader, pHeader->nDataLen);
  274. //LOG4C((LOG_NOTICE,"协议标识:%d,协议命令:%d,协议类型:%d,协议长度:%d,协议校验:%d",pHeader->bof,pHeader->nCmd,pHeader->nCmdType,pHeader->nDataLen,pHeader->nVerify));
  275. //unsigned char *pBody = &((unsigned char*)pIntegrityPacket)[sizeof(STProtocolheader)];
  276. if(tmp != pHeader->nVerify)
  277. {
  278. LOG4C((LOG_NOTICE,"协议校验值错误:len=%d,%d != %d",pHeader->nDataLen,tmp,pHeader->nVerify));
  279. return -1;
  280. }
  281. switch (pHeader->nCmd)
  282. {
  283. case CMD_HEART: // 公共命令:心跳包
  284. {
  285. // 心跳包,不处理任务事务;
  286. LOG4C((LOG_NOTICE,"接收到的心跳包"));
  287. }
  288. break;
  289. case CMD_TOCHAT: // 公共命令:文字聊天;
  290. {
  291. STChatbody *tChatbody = (STChatbody*)pIntegrityPacket;
  292. //TRACE("------------------");
  293. //AfxMessageBox(tChatbody->szChat);
  294. // CStdioFile fp;
  295. // CString path = CString(g_ModulePath) + _T("1111.txt");
  296. // if (PathFileExists(path))
  297. // {
  298. // fp.Open(path, CFile::modeWrite);
  299. // ULONGLONG length = fp.GetLength();
  300. // if (length > 5 * 1024 * 1024)
  301. // {
  302. // fp.Close();
  303. // ::DeleteFile(path);
  304. // return -1;
  305. // }
  306. // fp.SeekToEnd();
  307. // }
  308. // else
  309. // fp.Open(path, CFile::modeCreate | CFile::modeWrite);
  310. //
  311. // fp.WriteString((CTime::GetCurrentTime().Format(_T("%Y-%m-%d %H:%M:%S")) + _T(" ") + tChatbody->szChat + _T("\n")));
  312. // fp.Close();
  313. //LOG4C((LOG_NOTICE,"聊天内容:%s",tChatbody->szChat));
  314. }
  315. break;
  316. case CMD_FILEINFO_TRANSFER: // 公共命令:文件传输;
  317. {
  318. //LOG4C((LOG_NOTICE,"文件信息传输"));
  319. // 需要向客户端返回本地文件的信息:
  320. // 1.若不存在指定文件名,则返回FileSeek = 0;(文件位置指针)
  321. // 2.若文件存在,则读取文件大小,如果文件大小 == 客户端文件大小,表示已有完整文件,不进行传输;
  322. // 3.若文件存在,但文件大小 < 客户端文件大小,认为没有传守文件,继传。
  323. // 4.若文件存在,但文件大小 > 客户端文件大小,先删除本地文件,再与1相同处理。
  324. // 服务端要维护一个文件列表,用于记录客户端需要传输的文件;
  325. // 客户端同样维护一个文件列表,用于记录要传输的文件;
  326. // 两边文件列表一致;
  327. g_dwRecived = 0;
  328. if ( g_pSTFileInfobody == NULL )
  329. {
  330. g_pSTFileInfobody = new STFileInfobody();
  331. }
  332. memset(g_pSTFileInfobody,0,sizeof(STFileInfobody));
  333. memcpy(g_pSTFileInfobody,pIntegrityPacket,sizeof(STFileInfobody));
  334. //g_pSTFileInfobody = (STFileInfobody*)pIntegrityPacket;
  335. LOG4C((LOG_NOTICE,"%d:%d:%d:%d:%d, %s:%d:%d:%d",
  336. g_pSTFileInfobody->tPHeader.bof,
  337. g_pSTFileInfobody->tPHeader.nCmd,
  338. g_pSTFileInfobody->tPHeader.nCmdType,
  339. g_pSTFileInfobody->tPHeader.nDataLen,
  340. g_pSTFileInfobody->tPHeader.nVerify,
  341. g_pSTFileInfobody->szFileName,
  342. g_pSTFileInfobody->nFileLength,
  343. g_pSTFileInfobody->tCreateDate,
  344. g_pSTFileInfobody->tModifyDate));
  345. TCHAR szFileFullName[MAX_PATH] = _T("");
  346. sprintf(szFileFullName,"%s\%s",g_ModulePath,g_pSTFileInfobody->szFileName);
  347. memcpy(g_pSTFileInfobody->szFileName,szFileFullName,MAX_PATH);
  348. LOG4C((LOG_NOTICE,"文件名:%s",g_pSTFileInfobody->szFileName));
  349. }
  350. break;
  351. case CMD_FILECONT_TRANSFER:
  352. {
  353. //LOG4C((LOG_NOTICE,"文件内容传输"));
  354. // 文件传输需要单独出一个端口来独立完成,且只接收客户端排队文件传输。
  355. if ( g_pSTFileInfobody == NULL )
  356. {
  357. LOG4C((LOG_NOTICE,"接收文件信息失败"));
  358. return 0;
  359. }
  360. CFile file;
  361. CFileException e;
  362. file.Open(g_pSTFileInfobody->szFileName, CFile::modeNoTruncate|CFile::modeWrite|CFile::modeCreate|CFile::shareExclusive, &e);
  363. if (e.m_cause != 0)
  364. {
  365. DWORD dw = GetLastError();
  366. LOG4C((LOG_NOTICE,"创建或打开文件失败:%d",dw)); // dw = 53,表示写文件的速度还不及收的速度快。上次未写完,这次又要开始打开文件写.
  367. file.Close();
  368. return -1;
  369. }
  370. STFileContextbody *pFileContextbody = (STFileContextbody*)pIntegrityPacket;
  371. //__int64 nTotal = 0;
  372. //while( g_dwRecived < g_STFileInfobody.nFileLength )
  373. //{
  374. file.SeekToEnd();
  375. file.Write(pFileContextbody->szFileContext, pFileContextbody->nFileContextLen);
  376. g_dwRecived += pHeader->nDataLen;
  377. //}
  378. file.Close();
  379. //CFile::SetStatus(xInfo.szFileName,xInfo.fStat);
  380. }
  381. break;
  382. case C2LCMD_REQ_LOGIN:
  383. {
  384. // 1.判断登录信息(加密狗信息);
  385. // 2.信息从数据库中获取,比对正常允许通信;
  386. // **3.若信息比对失败,断开连接;
  387. // 3.若信息比对失败,允许连接,但不返回数据库信息;
  388. // 本端可对其进行控制。
  389. }
  390. break;
  391. case C2CCMD_REQ_LOGIN:
  392. {
  393. // 1.判断登录信息(账号+密码);
  394. // 2.信息从数据库中获取,比对正常允许通信,并返回数据库信息;
  395. // 3.若信息比对失败,断开连接;
  396. STAccountInfobody *tAccountInfobody = (STAccountInfobody*)pIntegrityPacket;
  397. if ( (strcmp(tAccountInfobody->szAccount,_T("admin")) == 0) && (strcmp(tAccountInfobody->szPassword,_T("admin123456")) == 0) )
  398. {
  399. TRACE("账号信息完全匹配");
  400. LOG4C((LOG_NOTICE,"账号信息完全匹配"));
  401. // 临时步骤,数据库信息应该做为全局变量保存; g_STDatabaseInfobody;
  402. STDatabaseInfobody tDatabaseInfobody;
  403. // ....配置好数据库信息;
  404. // ....................
  405. strcpy(tDatabaseInfobody.szDatabaseServer,"127.0.0.1");
  406. strcpy(tDatabaseInfobody.szDatabaseTCPPort,"1433");
  407. strcpy(tDatabaseInfobody.szDatabaseAccount,"sa");
  408. strcpy(tDatabaseInfobody.szDatabasePassword,"ly1234");
  409. strcpy(tDatabaseInfobody.szDatabaseName,"db");
  410. tDatabaseInfobody.GetVerify();
  411. //m_SocketServer->Write();
  412. CSocketHandle tSockhandle;
  413. tSockhandle.Attach(sockHandle);
  414. m_bStopbeat = TRUE;//停止心跳包;
  415. if( -1 == tSockhandle.Write((const LPBYTE)(&tDatabaseInfobody), tDatabaseInfobody.tPHeader.nDataLen, NULL))
  416. {
  417. // 发送失败;
  418. LOG4C((LOG_NOTICE,"发送失败ooo"));
  419. tSockhandle.Detach();
  420. }
  421. tSockhandle.Detach();
  422. m_bStopbeat = FALSE;//恢复心跳包;
  423. }
  424. else
  425. {
  426. TRACE("账号或密码错误");
  427. LOG4C((LOG_NOTICE,"账号或密码错误,关闭该套接字,拒绝连接"));
  428. // 关闭该套接字,拒绝连接;
  429. CSocketHandle::ShutdownConnection(sockHandle);
  430. }
  431. }
  432. break;
  433. default: return 0;
  434. }
  435. memset(sockHandle.szpendingbuf,0,SOCKET_BUFFSIZE);
  436. return 0;
  437. }
  438. // unsigned int IServerImpl::VerityIntegrityPacket(IN void *pIntegrityPacket,unsigned int nPacketSize)
  439. // {
  440. // unsigned int checksum = 0;
  441. // unsigned char *pBody = &((unsigned char*)pIntegrityPacket)[sizeof(STProtocolheader)];
  442. //
  443. // if( pBody )
  444. // checksum = crc32( 0, pBody, nPacketSize );
  445. //
  446. // return checksum;
  447. // }
  448. void IServerImpl::GetAddress(const SockAddrIn& addrIn, CString& rString) const
  449. {
  450. TCHAR szIPAddr[MAX_PATH] = { 0 };
  451. CSocketHandle::FormatIP(szIPAddr, MAX_PATH, addrIn);
  452. rString.Format(_T("%s : %d"), szIPAddr, static_cast<int>(static_cast<UINT>(ntohs(addrIn.GetPort()))) );
  453. }
  454. void IServerImpl::AppendText(LPCTSTR lpszFormat, ...)
  455. {
  456. // if ( !::IsWindow(m_ctlMsgList.GetSafeHwnd()) ) return;
  457. // TCHAR szBuffer[512];
  458. // HWND hWnd = m_ctlMsgList.GetSafeHwnd();
  459. // DWORD dwResult = 0;
  460. // if (SendMessageTimeout(hWnd, WM_GETTEXTLENGTH, 0, 0, SMTO_NORMAL, 500L, &dwResult) != 0)
  461. // {
  462. // int nLen = (int) dwResult;
  463. // if (SendMessageTimeout(hWnd, EM_SETSEL, nLen, nLen, SMTO_NORMAL, 500L, &dwResult) != 0)
  464. // {
  465. // size_t cb = 0;
  466. // va_list args;
  467. // va_start(args, lpszFormat);
  468. // ::StringCchVPrintfEx(szBuffer, 512, NULL, &cb, 0, lpszFormat, args);
  469. // va_end(args);
  470. // SendMessageTimeout(hWnd, EM_REPLACESEL, FALSE, reinterpret_cast<LPARAM>(szBuffer), SMTO_NORMAL, 500L, &dwResult);
  471. // }
  472. // }
  473. }
  474. bool IServerImpl::GetDestination(SockAddrIn& addrIn) const
  475. {
  476. CString strPort;
  477. //GetDlgItemText(IDC_SVR_PORT, strPort);
  478. int nFamily = (m_nMode == AF_IPV4) ? AF_INET : AF_INET6;
  479. return addrIn.CreateFrom(NULL, strPort, nFamily);
  480. }
  481. bool IServerImpl::SetupMCAST()
  482. {
  483. const TCHAR szIPv4MCAST[] = TEXT("239.121.1.2");
  484. const TCHAR szIPv6MCAST[] = TEXT("FF02:0:0:0:0:0:0:1"); // All Nodes local address
  485. bool result = false;
  486. if ( m_nSockType == SOCK_UDP )
  487. {
  488. if ( m_nMode == AF_IPV4 ) {
  489. result = m_SocketServer->AddMembership(szIPv4MCAST, NULL);
  490. } else {
  491. result = m_SocketServer->AddMembership(szIPv6MCAST, NULL);
  492. HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  493. hr = hr;
  494. }
  495. }
  496. return result;
  497. }
  498. ///////////////////////////////////////////////////////////////////////////////
  499. void IServerImpl::OnThreadBegin(CSocketHandle* pSH)
  500. {
  501. ASSERT( pSH == m_SocketServer );
  502. (pSH);
  503. CString strAddr;
  504. SockAddrIn sockAddr;
  505. m_SocketServer->GetSockName(sockAddr);
  506. GetAddress( sockAddr, strAddr );
  507. //AppendText( _T("Server Running on: %s\r\n"), strAddr);
  508. }
  509. void IServerImpl::OnThreadExit(CSocketHandle* pSH)
  510. {
  511. ASSERT( pSH == m_SocketServer );
  512. (pSH);
  513. //AppendText( _T("Server Down!\r\n"));
  514. }
  515. void IServerImpl::OnConnectionFailure(CSocketHandle* pSH, SOCKET newSocket)
  516. {
  517. ASSERT( pSH == m_SocketServer );
  518. (pSH);
  519. CString strAddr;
  520. CSocketHandle sockHandle;
  521. SockAddrIn sockAddr;
  522. if (newSocket != INVALID_SOCKET)
  523. {
  524. sockHandle.Attach( newSocket );
  525. sockHandle.GetPeerName( sockAddr );
  526. GetAddress( sockAddr, strAddr );
  527. sockHandle.Close();
  528. //AppendText( _T("Connection abandoned: %s\r\n"), strAddr );
  529. LOG4C((LOG_NOTICE,"Connection abandoned:%s",strAddr));
  530. }
  531. else
  532. {
  533. //AppendText( _T("Connection abandoned. Not a valid socket.\r\n"), strAddr );
  534. LOG4C((LOG_NOTICE,"Connection abandoned. Not a valid socket:%s",strAddr));
  535. }
  536. }
  537. void IServerImpl::OnAddConnection(CSocketHandle* pSH, SOCKET newSocket)
  538. {
  539. ASSERT( pSH == m_SocketServer );
  540. (pSH);
  541. CString strAddr;
  542. CSocketHandle sockHandle;
  543. SockAddrIn sockAddr;
  544. sockHandle.Attach( newSocket );
  545. sockHandle.GetPeerName( sockAddr );
  546. GetAddress( sockAddr, strAddr );
  547. sockHandle.Detach();
  548. //LOG4C((LOG_NOTICE,"新的连接接入:%s",strAddr));
  549. //AppendText( _T("Connection established: %s\r\n"), strAddr );
  550. }
  551. void IServerImpl::OnDataReceived(LPWSAOVERLAPPED pSH, const BYTE* pbData, DWORD dwCount, const SockAddrIn& addr)
  552. {
  553. ASSERT( pSH == NULL );
  554. CString strAddr, strText;
  555. USES_CONVERSION;
  556. LPTSTR pszText = strText.GetBuffer(dwCount+1);
  557. ::StringCchCopyN(pszText, dwCount+1, A2CT(reinterpret_cast<LPCSTR>(pbData)), dwCount);
  558. strText.ReleaseBuffer();
  559. GetAddress( addr, strAddr );
  560. AppendText( _T("%s>(%s)\r\n"), strAddr, strText);
  561. if (m_nSockType == SOCK_TCP)
  562. {
  563. SocketIOBuffer *psio = (SocketIOBuffer*)pSH;
  564. EnterCriticalSection( &m_csProcessData );
  565. ToprocessRecivebuf(*psio,pbData,dwCount);
  566. LeaveCriticalSection( &m_csProcessData );
  567. }
  568. else
  569. {
  570. SockAddrIn servAddr, sockAddr;
  571. m_SocketServer->GetSockName(servAddr);
  572. GetDestination(sockAddr);
  573. if ( servAddr != sockAddr )
  574. {
  575. //m_SocketServer.Write((const LPBYTE)(T2CA(strMsg)), strMsg.GetLength(), sockAddr);
  576. }
  577. else
  578. {
  579. //AppendText( _T("Please change the port number to send message to a client.\r\n") );
  580. }
  581. }
  582. }
  583. void IServerImpl::OnConnectionDropped(CSocketHandle* pSH)
  584. {
  585. ASSERT( pSH == m_SocketServer );
  586. (pSH);
  587. //AppendText( _T("Connection lost with client.\r\n") );
  588. //LOG4C((LOG_NOTICE,"Connection lost with client"));
  589. }
  590. void IServerImpl::OnConnectionError(CSocketHandle* pSH, DWORD dwError)
  591. {
  592. ASSERT( pSH == m_SocketServer );
  593. (pSH);
  594. _com_error err(dwError);
  595. //AppendText( _T("Communication Error:\r\n%s\r\n"), err.ErrorMessage() );
  596. //LOG4C((LOG_NOTICE,"Communication Error:%s",err.ErrorMessage()));
  597. }
  598. #if defined(SOCKHANDLE_USE_OVERLAPPED)
  599. void IServerImpl::OnRemoveConnection(CSocketHandle* pSH, SOCKET dropSocket)
  600. {
  601. return ;
  602. ASSERT( pSH == m_SocketServer );
  603. (pSH);
  604. CString strAddr;
  605. CSocketHandle sockHandle;
  606. SockAddrIn sockAddr;
  607. sockHandle.Attach( dropSocket );
  608. sockHandle.GetPeerName( sockAddr );
  609. GetAddress( sockAddr, strAddr );
  610. sockHandle.Detach();
  611. //LOG4C((LOG_NOTICE,"删除无效连接:%s",strAddr));
  612. }
  613. #endif
  614. DWORD IServerImpl::GetClientConnectCount()
  615. {
  616. return m_SocketServer.GetConnectionCount();
  617. }
  618. };