TCPServerIOCP.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. #include "stdafx.h"
  2. #include "TCPServerIOCP.h"
  3. //namespace iocpSock {
  4. // std::string format(const char* pszFmt, ...)
  5. // {
  6. // std::string str;
  7. // va_list args;
  8. // va_start(args, pszFmt);
  9. // {
  10. // int nLength = _vscprintf(pszFmt, args);
  11. // nLength += 1;//上面返回的长度是包含\0,这里加上
  12. // std::vector<char> vectorChars(nLength);
  13. // _vsnprintf(vectorChars.data(), nLength, pszFmt, args);
  14. // str.assign(vectorChars.data());
  15. // }
  16. // va_end(args);
  17. // return str;
  18. // }
  19. //}
  20. //
  21. //std::vector<ITCPServer *> m_vecTCPIOCP;
  22. void TCPServerIOCP::ListenThread_IOCPServer(LPVOID lpParam)
  23. {
  24. TCPServerIOCP* pServ = (TCPServerIOCP*)lpParam;
  25. if (pServ == NULL)
  26. return;
  27. //等待客户端连接
  28. SOCKADDR_IN clientAddr;
  29. int c_size = sizeof(SOCKADDR_IN);
  30. while (1)
  31. {
  32. memset(&clientAddr, 0, sizeof(SOCKADDR_IN));
  33. SOCKET sClient = accept(pServ->m_sListen, (SOCKADDR*)&clientAddr, &c_size);
  34. if (pServ->m_bStarted == FALSE)
  35. break;
  36. if (sClient != INVALID_SOCKET)//有效连接
  37. {
  38. pServ->DoAccept(sClient, &clientAddr);
  39. }
  40. else
  41. {
  42. int iErr = GetLastError();
  43. string str = fmt::format("[TCPServer][error]{} Failed accept, 错误码:{}", (LPCSTR)pServ->GetIOCPName(), iErr);
  44. pServ->Log((char*)str.c_str());
  45. continue;
  46. }
  47. }
  48. }
  49. void TCPServerIOCP::ListenThread_IOCPServer_IPv6(LPVOID lpParam)
  50. {
  51. TCPServerIOCP* pServ = (TCPServerIOCP*)lpParam;
  52. if (pServ == NULL)
  53. return;
  54. //等待客户端连接
  55. SOCKADDR_IN6 clientAddr;
  56. int c_size = sizeof(SOCKADDR_IN6);
  57. while (1)
  58. {
  59. memset(&clientAddr, 0, sizeof(SOCKADDR_IN6));
  60. SOCKET sClient = accept(pServ->m_sListen_IPv6, (SOCKADDR*)&clientAddr, &c_size);
  61. if (pServ->m_bStarted_IPv6 == FALSE)
  62. break;
  63. if (sClient != INVALID_SOCKET)//有效连接
  64. {
  65. pServ->DoAccept_IPv6(sClient, &clientAddr);
  66. }
  67. else
  68. {
  69. int iErr = GetLastError();
  70. string str = fmt::format("[TCPServer][error]{} Failed accept, 错误码:{}", (LPCSTR)pServ->GetIOCPName(), iErr);
  71. pServ->Log((char*)str.c_str());
  72. continue;
  73. }
  74. }
  75. }
  76. DWORD WINAPI ConnectionMaintainThread(LPVOID lpParam)
  77. {
  78. TCPServerIOCP* pServ = (TCPServerIOCP*)lpParam;
  79. pServ->ConnectionMaintain();
  80. return 0;
  81. }
  82. bool TCPServerIOCP::StartServer(ITcpServerCallBack* pUser, int iPort, CString strLocalIP /*= ""*/)
  83. {
  84. m_strServerIP = strLocalIP;
  85. m_iServerPort = iPort;
  86. m_pCallBackUser = pUser;
  87. USES_CONVERSION;
  88. if (iAutoClearDeadConnectionTime > 0)
  89. {
  90. DWORD dwThread = 0;
  91. HANDLE hThread = CreateThread(NULL, 0, ::ConnectionMaintainThread, (LPVOID)this, 0, &dwThread);
  92. if (hThread) CloseHandle(hThread);
  93. }
  94. string strip = strLocalIP;
  95. return StartListen(iPort, strip);
  96. }
  97. bool TCPServerIOCP::StartServer_IPv6(ITcpServerCallBack* pUser, int iPort, CString strLocalIP /*= ""*/)
  98. {
  99. m_strServerIP_IPv6 = strLocalIP;
  100. m_iServerPort_IPv6 = iPort;
  101. m_pCallBackUser_IPv6 = pUser;
  102. USES_CONVERSION;
  103. //超时断开连接
  104. if (iAutoClearDeadConnectionTime > 0)
  105. {
  106. DWORD dwThread = 0;
  107. HANDLE hThread = CreateThread(NULL, 0, ::ConnectionMaintainThread, (LPVOID)this, 0, &dwThread);
  108. if (hThread) CloseHandle(hThread);
  109. }
  110. return StartListen_IPv6(iPort, (string)strLocalIP);
  111. }
  112. void TCPServerIOCP::StopServer()
  113. {
  114. closesocket(m_sListen);
  115. CloseServer();
  116. m_bStarted = FALSE;
  117. closesocket(m_sListen_IPv6);
  118. WSACleanup();
  119. m_bStarted_IPv6 = FALSE;
  120. }
  121. BOOL TCPServerIOCP::SendData(const char* pData, int iLen, ClientInfo* pCltInfo)
  122. {
  123. //socket是阻塞式socket,当socket发送缓冲区满时,该函数会阻塞;在发送大数据时会出现阻塞状态
  124. if (iLen == 0) return FALSE;
  125. if (!pCltInfo) return FALSE;
  126. BOOL bRet = SendData(pData, iLen, pCltInfo->strIP, pCltInfo->iPort, pCltInfo->sock);
  127. StaticConnData(pCltInfo->strIP, pData, iLen, CONN_DATA_SEND);
  128. if (bRet)
  129. pCltInfo->iSendSucCount += iLen;
  130. else
  131. pCltInfo->iSendFailCount += iLen;
  132. return bRet;
  133. }
  134. BOOL TCPServerIOCP::SendData(const char* pData, int iLen, CString strIP)
  135. {
  136. BOOL bRet = FALSE;
  137. m_csClientVectorLock.Lock();
  138. std::vector<COverlappedIOInfo*>::iterator iter = m_vecContInfo.begin();
  139. //所有该ip的客户端都发送,一个ip有两个连接,发送给了僵尸连接却没有发送给正常连接
  140. for (; iter != m_vecContInfo.end(); ++iter)
  141. {
  142. if ((*iter) && (*iter)->m_cltInfo.strIP == strIP && (*iter)->m_cltInfo.sock != NULL)
  143. {
  144. bRet = SendData(pData, iLen, &(*iter)->m_cltInfo);
  145. }
  146. }
  147. m_csClientVectorLock.Unlock();
  148. return bRet;
  149. }
  150. BOOL TCPServerIOCP::SendData(const char* pData, int iLen, SOCKET& sock)
  151. {
  152. BOOL bRet = FALSE;
  153. m_csClientVectorLock.Lock();
  154. std::vector<COverlappedIOInfo*>::iterator iter = m_vecContInfo.begin();
  155. bool bSend = false;
  156. //所有该ip的客户端都发送,一个ip有两个连接,发送给了僵尸连接却没有发送给正常连接
  157. for (; iter != m_vecContInfo.end(); ++iter)
  158. {
  159. if ((*iter) && (*iter)->m_cltInfo.sock == sock)
  160. {
  161. bRet = SendData(pData, iLen, &(*iter)->m_cltInfo);
  162. bSend = true;
  163. }
  164. }
  165. if (!bSend)
  166. {
  167. SendData(pData, iLen, "专项发送", 0, sock);
  168. }
  169. m_csClientVectorLock.Unlock();
  170. return bRet;
  171. }
  172. BOOL TCPServerIOCP::SendData(const char* pData, int iLen, CString strIP, int port, SOCKET& sock)
  173. {
  174. if (sock == 0)
  175. return FALSE;
  176. //长沙南150机站chrono::steady_clock::now()出现奔溃
  177. //暂时假设系统资源紧张导致,先注释 2023.9.13 卢涛
  178. //auto s = chrono::steady_clock::now();
  179. int iRet = send(sock, pData, iLen, 0);
  180. //auto s2 = chrono::steady_clock::now();
  181. //auto s_dif = chrono::duration_cast<chrono::milliseconds>(s2 - s).count();
  182. int iErr = GetLastError();
  183. /*if (s_dif > 500)
  184. {
  185. if (m_callBackTcpLog)
  186. {
  187. auto str = fmt::format("[TCPServerIOCP][send]数据发送间隔超过500ms. 对方地址{}:{} 耗时{} ms 长度:{} send返回值:{}", (LPCSTR)strIP, port, s_dif, iLen, iRet);
  188. m_callBackTcpLog(3, strIP, port, (void*)str.c_str(), str.length(), iRet, iErr);
  189. }
  190. }*/
  191. if (m_callBackTcpLog != nullptr)
  192. {
  193. m_callBackTcpLog(0, strIP, port, pData, iLen, iRet, iErr);
  194. }
  195. if (iRet == -1)
  196. {
  197. string strError;
  198. if (iErr == WSAETIMEDOUT)
  199. {
  200. strError = "超时";//客户端不接受数据或者接受处理缓慢可能导致此问题
  201. string str = fmt::format("[TCPServer][error]socket:{} 数据发送失败,错误码:{}({})", sock, iErr, strError.c_str());
  202. if (m_callBackTcpLog) m_callBackTcpLog(3, strIP, port, (void*)str.c_str(), str.length(), iRet, iErr);
  203. closesocket(sock);
  204. sock = 0;
  205. }
  206. else if (iErr == WSAENOTSOCK)
  207. {
  208. auto str = fmt::format("[TCPServer][error]在一个非套接字上尝试了一个操作。,iErr={}", iErr);
  209. if (m_callBackTcpLog) m_callBackTcpLog(3, strIP, port, (void*)str.c_str(), str.length(), iRet, iErr);
  210. closesocket(sock);
  211. sock = 0;
  212. }
  213. else if (iErr == WSAECONNABORTED)
  214. {
  215. auto str = fmt::format("[TCPServer][error]你的主机中的软件中止了一个已建立的连接,iErr={}", iErr);
  216. if (m_callBackTcpLog) m_callBackTcpLog(3, strIP, port, (void*)str.c_str(), str.length(), iRet, iErr);
  217. closesocket(sock);
  218. sock = 0;
  219. }
  220. else
  221. {
  222. closesocket(sock);
  223. sock = 0;
  224. }
  225. return FALSE;
  226. }
  227. return TRUE;
  228. }
  229. //广播发送
  230. BOOL TCPServerIOCP::SendData(const char* pData, int iLen)
  231. {
  232. //std::vector<COverlappedIOInfo*>& vecClt = m_vecContInfo;
  233. //std::vector<COverlappedIOInfo*>::iterator iter = vecClt.begin();
  234. ClientInfo* ptrClientInfo = NULL;
  235. //for (; iter != vecClt.end(); ++iter)
  236. //for(auto & iter: m_vecContInfo)
  237. //{
  238. // //ptrClientInfo = &(*iter)->m_cltInfo;
  239. // ptrClientInfo = &(iter->m_cltInfo);
  240. // SendData(pData, iLen, ptrClientInfo);
  241. //}
  242. m_csClientVectorLock.Lock();
  243. for (auto iter = m_vecContInfo.begin(); iter != m_vecContInfo.end();)
  244. {
  245. //ptrClientInfo = &(*iter)->m_cltInfo;
  246. ptrClientInfo = &((*iter)->m_cltInfo);
  247. if (FALSE == SendData(pData, iLen, ptrClientInfo))
  248. {
  249. m_csCacheListLock.Lock();
  250. m_listContInfo.push_back({ std::shared_ptr<COverlappedIOInfo>(*iter), GetTickCount() });
  251. m_csCacheListLock.Unlock();
  252. iter = m_vecContInfo.erase(iter);
  253. }
  254. else
  255. iter++;
  256. }
  257. m_csClientVectorLock.Unlock();
  258. return TRUE;
  259. }
  260. /*构造函数*/
  261. void TCPServerIOCP::Log(char* sz)
  262. {
  263. if (pLog)
  264. {
  265. pLog(sz);
  266. }
  267. }
  268. TCPServerIOCP::TCPServerIOCP() :
  269. m_callBackTcpLog(nullptr)
  270. {
  271. WSAStartup(MAKEWORD(2, 2), &m_wsaData);
  272. m_mapConnHistory.clear();
  273. //if(bAddVec)
  274. //{
  275. // m_vecTCPIOCP.push_back(this);
  276. // HWND hWnd = FindWindow(NULL, TCPIOCP_MANAGER);
  277. // if (hWnd) PostMessage(hWnd, ADD_TCPIOCP, 0, 0);
  278. //}
  279. m_bStarted = FALSE;
  280. //pLog = NULL;
  281. }
  282. /*析构函数*/
  283. TCPServerIOCP::~TCPServerIOCP()
  284. {
  285. CloseServer();
  286. WSACleanup();
  287. for (auto it = m_mapConnHistory.begin(); it != m_mapConnHistory.end(); it++) {
  288. if (it->second) delete it->second;
  289. }
  290. m_mapConnHistory.clear();
  291. }
  292. /*TCP Server开启监听*/
  293. bool TCPServerIOCP::StartListen(unsigned short port, string ip)
  294. {
  295. //listen socket需要将accept操作投递到完成端口,因此listen socket属性必须有重叠IO
  296. m_sListen = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);
  297. if (m_sListen == INVALID_SOCKET)
  298. {
  299. return false;
  300. }
  301. //创建并设置IOCP并发线程数量
  302. if (m_iocp.Create() == false)
  303. {
  304. return false;
  305. }
  306. if (!m_iocp.AssociateSocket(m_sListen, TYPE_ACP))
  307. {
  308. return false;
  309. }
  310. sockaddr_in service;
  311. service.sin_family = AF_INET;
  312. service.sin_port = htons(port);
  313. if (ip.empty())
  314. {
  315. service.sin_addr.s_addr = INADDR_ANY;
  316. }
  317. else
  318. {
  319. service.sin_addr.s_addr = inet_addr(ip.c_str());
  320. }
  321. if (::bind(m_sListen, (sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
  322. {
  323. m_lastError = GetLastError();
  324. return false;
  325. }
  326. if (listen(m_sListen, SOMAXCONN) == SOCKET_ERROR)
  327. {
  328. }
  329. //启动工作者线程
  330. int threadnum = StartWorkThreadPool();
  331. Sleep(20);
  332. m_bStarted = TRUE;
  333. _beginthread(TCPServerIOCP::ListenThread_IOCPServer, 0, this);
  334. return true;
  335. }
  336. /*TCP Server_IPv6开启监听*/
  337. bool TCPServerIOCP::StartListen_IPv6(unsigned short port, string ip)
  338. {
  339. WSADATA wsaData;
  340. // 初始化Winsock
  341. int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
  342. if (result != 0) {
  343. return 1;
  344. }
  345. // 创建socket
  346. m_sListen_IPv6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
  347. if (m_sListen_IPv6 == INVALID_SOCKET) {
  348. WSACleanup();
  349. return 1;
  350. }
  351. //创建并设置IOCP并发线程数量
  352. if (m_iocp_IPv6.Create() == false)
  353. {
  354. return false;
  355. }
  356. if (!m_iocp_IPv6.AssociateSocket(m_sListen_IPv6, TYPE_ACP))
  357. {
  358. return false;
  359. }
  360. // 准备地址信息
  361. sockaddr_in6 addr;
  362. ZeroMemory(&addr, sizeof(addr));
  363. addr.sin6_family = AF_INET6;
  364. addr.sin6_addr = in6addr_any; // 监听任何地址
  365. addr.sin6_port = htons(port); // 端口9999
  366. // 绑定socket
  367. _WINSOCK2API_::bind(m_sListen_IPv6, (SOCKADDR*)&addr, sizeof(addr));
  368. // 开始监听
  369. if (listen(m_sListen_IPv6, SOMAXCONN) == SOCKET_ERROR) {
  370. int error = WSAGetLastError();
  371. closesocket(m_sListen_IPv6);
  372. WSACleanup();
  373. return 1;
  374. }
  375. //启动工作者线程
  376. int threadnum = StartWorkThreadPool_IPv6();
  377. Sleep(20);
  378. m_bStarted_IPv6 = TRUE;
  379. _beginthread(TCPServerIOCP::ListenThread_IOCPServer_IPv6, 0, this);
  380. return true;
  381. }
  382. int TCPServerIOCP::CalcTimePassSecond(SYSTEMTIME* stLast, SYSTEMTIME* stNow)
  383. {
  384. SYSTEMTIME stNowTime;
  385. if (stNow)
  386. {
  387. stNowTime = *stNow;
  388. }
  389. else
  390. {
  391. GetLocalTime(&stNowTime);
  392. }
  393. CTime dTimeNow(stNowTime);
  394. CTime dTimeLast(*stLast);
  395. CTimeSpan dTimeSpan = dTimeNow - dTimeLast;
  396. int iSecnonSpan = dTimeSpan.GetTotalSeconds();
  397. return abs(iSecnonSpan);
  398. }
  399. void TCPServerIOCP::ConnectionMaintain()
  400. {
  401. while (1)
  402. {
  403. Sleep(5000);
  404. m_csClientVectorLock.Lock();
  405. std::vector<COverlappedIOInfo*>::iterator iter = m_vecContInfo.begin();
  406. vector<COverlappedIOInfo*> vecDeadList;
  407. for (; iter != m_vecContInfo.end(); ++iter)
  408. {
  409. ClientInfo* pci = &(*iter)->m_cltInfo;
  410. int iUnactiveTime = CalcTimePassSecond(&pci->stLastActive);
  411. if (iUnactiveTime > iAutoClearDeadConnectionTime && iAutoClearDeadConnectionTime != 0)
  412. {
  413. vecDeadList.push_back(*iter);
  414. }
  415. }
  416. for (int i = 0; i < vecDeadList.size(); i++)
  417. {
  418. COverlappedIOInfo* p = vecDeadList.at(i);
  419. if (p->m_cltInfo.sock == NULL)
  420. continue;
  421. if (m_callBackTcpLog != nullptr)
  422. {
  423. m_callBackTcpLog(2, p->m_cltInfo.strIP, p->m_cltInfo.iPort, "心跳超时断开", 0, 0, 1);
  424. }
  425. string str = fmt::format("[TCPServer][trace][{}][socketid:{}]心跳超时断开", (LPCSTR)GetIOCPName(), (int)p->m_cltInfo.sock);
  426. Log((char *)str.c_str());
  427. //关闭socket,GetQueuedCompletionStatus返回false,未决的WSA_RECV似乎是丢弃了
  428. closesocket(p->m_cltInfo.sock);
  429. p->m_cltInfo.sock = NULL;
  430. p->m_cltInfo.isValid = false;
  431. int iErr = WSAGetLastError();
  432. string strErrorInfo = "";
  433. //关闭当前连接
  434. //m_iocp.PostStatus(TYPE_CLOSE_SOCK, 0, p);
  435. }
  436. m_csClientVectorLock.Unlock();
  437. }
  438. }
  439. //COverlappedIOInfo 对象必须由WorkThread来删除。如果其他线程删除该对象。GetQueuedCompletionStatus返回会拿到野指针
  440. //因为该对象被 PostRecv放到完成端口中使用了
  441. DWORD WINAPI WorkThread(LPVOID lpParam)
  442. {
  443. TCPServerIOCP* pServ = (TCPServerIOCP*)lpParam;
  444. while (true)
  445. {
  446. DWORD NumberOfBytes = 0;
  447. ULONG_PTR completionKey = 0;
  448. OVERLAPPED* ol = NULL;
  449. //阻塞调用GetQueuedCompletionStatus获取完成端口事件
  450. //GetQueuedCompletionStatus成功返回
  451. if (GetQueuedCompletionStatus(pServ->m_iocp.GetIOCP(), &NumberOfBytes, &completionKey, &ol, WSA_INFINITE))
  452. {
  453. COverlappedIOInfo* olinfo = (COverlappedIOInfo*)ol;
  454. if (completionKey == TYPE_CLOSE)
  455. {
  456. break;
  457. }
  458. //客户端断开连接
  459. if (NumberOfBytes == 0 && (completionKey == TYPE_RECV || completionKey == TYPE_SEND))
  460. {
  461. string str = fmt::format("[TCPServer][trace][{}][socketid:{}]错误信息:客户端主动断开socket连接", (LPCSTR)pServ->GetIOCPName(), (int)olinfo->m_socket);
  462. pServ->Log((char*)str.c_str());
  463. pServ->DeleteLink(olinfo->m_socket, "客户端主动断开socket连接");
  464. continue;
  465. }
  466. if (completionKey == TYPE_CLOSE_SOCK)
  467. {
  468. pServ->DeleteLink(olinfo->m_socket, "TYPE_CLOSE_SOCK主动关闭连接");
  469. continue;
  470. }
  471. switch (completionKey)
  472. {
  473. case TYPE_ACP:
  474. {
  475. }break;
  476. case TYPE_RECV:
  477. {
  478. //运行到此处,数据已经从socket缓冲区接收到overlapped info中
  479. olinfo->m_recvBuf.len = NumberOfBytes;
  480. pServ->DoRecv(olinfo);
  481. pServ->PostRecv(olinfo);
  482. }break;
  483. case TYPE_SEND:
  484. {
  485. }break;
  486. default:
  487. break;
  488. }
  489. }
  490. else//GetQueuedCompletionStatus出错
  491. {
  492. int res = WSAGetLastError();
  493. CString strError;
  494. strError.Format("[err:%d]", res);
  495. COverlappedIOInfo *olinfo = (COverlappedIOInfo *)ol;
  496. SOCKET sk = olinfo ? olinfo->m_socket : 0;
  497. switch (res)
  498. {
  499. case ERROR_NETNAME_DELETED:
  500. {
  501. string str = fmt::format("[TCPServer][trace][{}][socketid:{}]错误信息:指定的网络名不再可用", (LPCSTR)pServ->GetIOCPName(), (int)sk);
  502. strError += "客户端主动断开socket连接";
  503. pServ->Log((char*)str.c_str());
  504. }
  505. break;
  506. case ERROR_CONNECTION_ABORTED:
  507. {
  508. string str = fmt::format("[TCPServer][debug][{}][socketid:{}]错误信息:服务端主动断开socket连接", (LPCSTR)pServ->GetIOCPName(), (int)sk);
  509. strError += "服务端主动断开socket连接";
  510. pServ->Log((char*)str.c_str());
  511. }
  512. break;
  513. default:
  514. break;
  515. }
  516. if (olinfo)
  517. {
  518. pServ->DeleteLink(olinfo->m_socket, strError.GetBuffer());
  519. }
  520. }
  521. }
  522. return 0;
  523. }
  524. DWORD WINAPI WorkThread_IPv6(LPVOID lpParam)
  525. {
  526. TCPServerIOCP* pServ = (TCPServerIOCP*)lpParam;
  527. while (true)
  528. {
  529. DWORD NumberOfBytes = 0;
  530. ULONG_PTR completionKey = 0;
  531. OVERLAPPED* ol = NULL;
  532. //阻塞调用GetQueuedCompletionStatus获取完成端口事件
  533. //GetQueuedCompletionStatus成功返回
  534. if (GetQueuedCompletionStatus(pServ->m_iocp_IPv6.GetIOCP(), &NumberOfBytes, &completionKey, &ol, WSA_INFINITE))
  535. {
  536. COverlappedIOInfo* olinfo = (COverlappedIOInfo*)ol;
  537. if (completionKey == TYPE_CLOSE)
  538. {
  539. break;
  540. }
  541. //客户端断开连接
  542. if (NumberOfBytes == 0 && (completionKey == TYPE_RECV || completionKey == TYPE_SEND))
  543. {
  544. string str = fmt::format("[TCPServer][trace][{}][socketid:{}]错误信息:客户端主动断开socket连接", (LPCSTR)pServ->GetIOCPName(), (int)olinfo->m_socket);
  545. pServ->Log((char*)str.c_str());
  546. pServ->DeleteLink(olinfo->m_socket, "客户端主动断开socket连接");
  547. continue;
  548. }
  549. if (completionKey == TYPE_CLOSE_SOCK)
  550. {
  551. pServ->DeleteLink(olinfo->m_socket, "TYPE_CLOSE_SOCK主动关闭连接");
  552. continue;
  553. }
  554. switch (completionKey)
  555. {
  556. case TYPE_ACP:
  557. {
  558. }break;
  559. case TYPE_RECV:
  560. {
  561. //运行到此处,数据已经从socket缓冲区接收到overlapped info中
  562. olinfo->m_recvBuf.len = NumberOfBytes;
  563. pServ->DoRecv(olinfo);
  564. pServ->PostRecv(olinfo);
  565. }break;
  566. case TYPE_SEND:
  567. {
  568. }break;
  569. default:
  570. break;
  571. }
  572. }
  573. else//GetQueuedCompletionStatus出错
  574. {
  575. int res = WSAGetLastError();
  576. CString strError;
  577. strError.Format("[err:%d]", res);
  578. COverlappedIOInfo* olinfo = (COverlappedIOInfo*)ol;
  579. SOCKET sk = olinfo ? olinfo->m_socket : 0;
  580. switch (res)
  581. {
  582. case ERROR_NETNAME_DELETED:
  583. {
  584. string str = fmt::format("[TCPServer][trace][{}][socketid:{}]错误信息:指定的网络名不再可用", (LPCSTR)pServ->GetIOCPName(), (int)sk);
  585. strError += "客户端主动断开socket连接";
  586. pServ->Log((char*)str.c_str());
  587. }
  588. break;
  589. case ERROR_CONNECTION_ABORTED:
  590. {
  591. string str = fmt::format("[TCPServer][debug][{}][socketid:{}]错误信息:服务端主动断开socket连接", (LPCSTR)pServ->GetIOCPName(), (int)sk);
  592. strError += "服务端主动断开socket连接";
  593. pServ->Log((char*)str.c_str());
  594. }
  595. break;
  596. default:
  597. break;
  598. }
  599. if (olinfo)
  600. {
  601. pServ->DeleteLink(olinfo->m_socket, strError.GetBuffer());
  602. }
  603. }
  604. }
  605. return 0;
  606. }
  607. /*启动工作者线程池*/
  608. int TCPServerIOCP::StartWorkThreadPool()
  609. {
  610. DWORD dwThread = 0;
  611. HANDLE hThread = CreateThread(NULL, 0, WorkThread, (LPVOID)this, 0, &dwThread);
  612. CloseHandle(hThread);
  613. return 0;
  614. }
  615. int TCPServerIOCP::StartWorkThreadPool_IPv6()
  616. {
  617. DWORD dwThread = 0;
  618. HANDLE hThread = CreateThread(NULL, 0, WorkThread_IPv6, (LPVOID)this, 0, &dwThread);
  619. CloseHandle(hThread);
  620. return 0;
  621. }
  622. bool TCPServerIOCP::DoAccept(SOCKET sockAccept, SOCKADDR_IN* ClientAddr)
  623. {
  624. //临时加的代码屏蔽某个IP
  625. if (ClientAddr->sin_addr.S_un.S_addr == m_blackaddr)
  626. {
  627. if (m_callBackTcpLog != nullptr)
  628. m_callBackTcpLog(1, inet_ntoa(ClientAddr->sin_addr), htons(ClientAddr->sin_port), "连接成功, 但在黑名单内直接关闭", 0, 0, 1);
  629. closesocket(sockAccept);
  630. return false;
  631. }
  632. //删除缓冲里面超过30分钟的数据
  633. m_csCacheListLock.Lock();
  634. DWORD dwNowTick = GetTickCount();
  635. m_listContInfo.remove_if([&dwNowTick](const CConnectCache& it) {
  636. return dwNowTick - it.dwDisConnect > 30 * 60 * 1000;
  637. });
  638. m_csCacheListLock.Unlock();
  639. //新连接的socket是accept函数默认创建的,因此该socket是阻塞式socket
  640. COverlappedIOInfo* olinfo = new COverlappedIOInfo();//其他地方内存泄漏很容易导致此处崩溃,原因未知,如果发现此处异常,很可能某处存在内存泄漏
  641. if (!olinfo) return false;
  642. int nNetTimeout = 3000;//3秒,由于客户端的异常,没有及时接受数据导致服务端发送缓冲区满了之后,可能导致send超时返回。为防止客户端缺陷不收数据导致服务端send函数永久阻塞,增加该超时设置
  643. //设置发送超时
  644. setsockopt(sockAccept, SOL_SOCKET, SO_SNDTIMEO, (char*)&nNetTimeout, sizeof(int));
  645. olinfo->m_socket = sockAccept;
  646. olinfo->m_addr = *ClientAddr;
  647. olinfo->m_cltInfo.pTcpServer1 = this;
  648. CString strIP;
  649. strIP.Format(_T("%d.%d.%d.%d"), olinfo->m_addr.sin_addr.S_un.S_un_b.s_b1, olinfo->m_addr.sin_addr.S_un.S_un_b.s_b2, olinfo->m_addr.sin_addr.S_un.S_un_b.s_b3, olinfo->m_addr.sin_addr.S_un.S_un_b.s_b4);
  650. memcpy(olinfo->m_cltInfo.strIP, strIP.GetBuffer(0), strIP.GetLength());
  651. olinfo->m_cltInfo.strIP[strIP.GetLength()] = '\0';
  652. olinfo->m_cltInfo.sock = olinfo->m_socket;
  653. olinfo->m_cltInfo.iPort = ntohs(olinfo->m_addr.sin_port);
  654. if (m_callBackTcpLog != nullptr)
  655. {
  656. m_callBackTcpLog(1, strIP, olinfo->m_cltInfo.iPort, "连接成功", 0, 0, 1);
  657. }
  658. //服务端只收取recv,同时监听recv和send可用设计位偏移,用或运算实现
  659. if (m_iocp.AssociateSocket(olinfo->m_socket, TYPE_RECV))
  660. {
  661. //绑定历史记录
  662. BindHistoryData(olinfo);
  663. m_csClientVectorLock.Lock();
  664. m_vecContInfo.push_back(olinfo);
  665. m_csClientVectorLock.Unlock();
  666. m_pCallBackUser->ConnStatusChange(&olinfo->m_cltInfo, true);
  667. PostRecv(olinfo);
  668. }
  669. else
  670. {
  671. delete olinfo;
  672. return false;
  673. }
  674. return true;
  675. }
  676. bool TCPServerIOCP::DoAccept_IPv6(SOCKET sockAccept, SOCKADDR_IN6* ClientAddr)
  677. {
  678. //删除缓冲里面超过30分钟的数据
  679. m_csCacheListLock.Lock();
  680. DWORD dwNowTick = GetTickCount();
  681. m_listContInfo.remove_if([&dwNowTick](const CConnectCache& it) {
  682. return dwNowTick - it.dwDisConnect > 30 * 60 * 1000;
  683. });
  684. m_csCacheListLock.Unlock();
  685. //新连接的socket是accept函数默认创建的,因此该socket是阻塞式socket
  686. COverlappedIOInfo* olinfo = new COverlappedIOInfo();//其他地方内存泄漏很容易导致此处崩溃,原因未知,如果发现此处异常,很可能某处存在内存泄漏
  687. if (!olinfo) return false;
  688. int nNetTimeout = 3000;//3秒,由于客户端的异常,没有及时接受数据导致服务端发送缓冲区满了之后,可能导致send超时返回。为防止客户端缺陷不收数据导致服务端send函数永久阻塞,增加该超时设置
  689. //设置发送超时
  690. setsockopt(sockAccept, SOL_SOCKET, SO_SNDTIMEO, (char*)&nNetTimeout, sizeof(int));
  691. olinfo->m_socket = sockAccept;
  692. olinfo->bIPv6addr = TRUE;
  693. olinfo->m_addr_IPv6 = *ClientAddr;
  694. olinfo->m_cltInfo.pTcpServer1 = this;
  695. unsigned char* ipBytes = olinfo->m_addr_IPv6.sin6_addr.u.Byte;
  696. CString strIP;
  697. strIP.Format(_T("%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x"),
  698. ipBytes[0], ipBytes[1], ipBytes[2], ipBytes[3],
  699. ipBytes[4], ipBytes[5], ipBytes[6], ipBytes[7],
  700. ipBytes[8], ipBytes[9], ipBytes[10], ipBytes[11],
  701. ipBytes[12], ipBytes[13], ipBytes[14], ipBytes[15]);
  702. memcpy(olinfo->m_cltInfo.strIP, strIP.GetBuffer(0), strIP.GetLength());
  703. olinfo->m_cltInfo.strIP[strIP.GetLength()] = '\0';
  704. olinfo->m_cltInfo.sock = olinfo->m_socket;
  705. olinfo->m_cltInfo.iPort = ntohs(olinfo->m_addr.sin_port);
  706. if (m_callBackTcpLog != nullptr)
  707. {
  708. m_callBackTcpLog(1, strIP, olinfo->m_cltInfo.iPort, "连接成功", 0, 0, 1);
  709. }
  710. //服务端只收取recv,同时监听recv和send可用设计位偏移,用或运算实现
  711. if (m_iocp_IPv6.AssociateSocket(olinfo->m_socket, TYPE_RECV))
  712. {
  713. //绑定历史记录
  714. BindHistoryData(olinfo);
  715. m_csClientVectorLock.Lock();
  716. m_vecContInfo.push_back(olinfo);
  717. m_csClientVectorLock.Unlock();
  718. m_pCallBackUser->ConnStatusChange(&olinfo->m_cltInfo, true);
  719. PostRecv(olinfo);
  720. }
  721. else
  722. {
  723. delete olinfo;
  724. return false;
  725. }
  726. return true;
  727. }
  728. /*投递一个接收数据完成端口*/
  729. /*
  730. WSARecv 只是向系统提交一个异步接收请求,这个请求会在有数据到达之后返回,并且放入完成队列通知工作线程,这个异步接收请求到此完成,继续提交请求是为了接收下一个数据包,也就是说,每次请求返回之后必须再次提交。
  731. 类似这样:
  732. 1. 你让一个前台去等待接待一个客人(WSARecv)然后继续做你的事情
  733. 2. 你的秘书会一直等着资料夹有新文件然后拿给你然后继续等待有新文件(loop)
  734. 3. 前台接待客人之后把客户资料放到资料夹之后就不会继续去前台接待客人了
  735. 4. 这个时候如果你不再派前台继续去等待接待客人(WSARecv),那么你的资料夹不会有新的资料了,这时就需要再次指派前台去等待接待新的客人(再次WSARecv)
  736. */
  737. bool TCPServerIOCP::PostRecv(COverlappedIOInfo* info)
  738. {
  739. if (GetStopRecvStatus())
  740. return true;
  741. DWORD BytesRecevd = 0;
  742. DWORD dwFlags = 0;
  743. info->ResetOverlapped();
  744. info->ResetRecvBuffer();
  745. int recvNum = WSARecv(info->m_socket, &info->m_recvBuf, 1, &info->m_recvBuf.len, &dwFlags, (OVERLAPPED*)info, NULL);
  746. int iLastError = 0;
  747. if (recvNum != 0)
  748. {
  749. iLastError = WSAGetLastError();
  750. if (WSA_IO_PENDING != iLastError)
  751. {
  752. }
  753. else if (WSAENOTSOCK == iLastError) { //socket被超时线程关闭 或 其他原因
  754. DeleteLink(info->m_socket, "socket被超时线程关闭 或 其他原因");
  755. }
  756. else if (WSAECONNRESET == iLastError) //呗远程主机强制关闭
  757. {
  758. DeleteLink(info->m_socket, "socket呗远程主机强制关闭");
  759. }
  760. else {
  761. }
  762. }
  763. return true;
  764. }
  765. //新连接绑定历史记录
  766. void TCPServerIOCP::BindHistoryData(COverlappedIOInfo* info, bool bRecv/* = false*/)
  767. {
  768. CString strIP = info->m_cltInfo.strIP;
  769. auto pFindNew = m_mapConnHistory.find(strIP);
  770. if (pFindNew == m_mapConnHistory.end()) {
  771. ConnHistoryInfo* newInfo = new ConnHistoryInfo;
  772. newInfo->strIp = strIP;
  773. newInfo->socket = info->m_socket;
  774. newInfo->bOnline = true;
  775. newInfo->bProxy = false;
  776. newInfo->bRecving = bRecv;
  777. newInfo->pCltInfo = &info->m_cltInfo;
  778. ::GetLocalTime(&newInfo->lastConnectTime);
  779. m_mapConnHistory[strIP] = newInfo;
  780. }
  781. else {
  782. pFindNew->second->Lock();
  783. pFindNew->second->socket = info->m_socket;
  784. pFindNew->second->iReconnnectCount++;
  785. pFindNew->second->bOnline = true;
  786. pFindNew->second->bProxy = false;
  787. pFindNew->second->bRecving = bRecv;
  788. pFindNew->second->pCltInfo = &info->m_cltInfo;
  789. ::GetLocalTime(&pFindNew->second->lastConnectTime);
  790. pFindNew->second->Unlock();
  791. }
  792. }
  793. /*接收数据处理句柄*/
  794. bool TCPServerIOCP::DoRecv(COverlappedIOInfo* info)
  795. {
  796. //auto pFindOld = m_mapConnHistory.find(info->m_cltInfo.strIP);
  797. //if (pFindOld != m_mapConnHistory.end())
  798. //{
  799. // if (!pFindOld->second->bRecving)
  800. // {
  801. // pFindOld->second->bRecving = true;
  802. // HWND hWnd = FindWindow(NULL, TCPIOCP_MANAGER);
  803. // if (hWnd) {
  804. // SendMessage(hWnd, ADD_CONNECT_TCPTOCP, 0, (WPARAM)info->m_cltInfo.strIP);
  805. // }
  806. // }
  807. //}
  808. info->m_cltInfo.iRecvCount += info->m_recvBuf.len;
  809. m_pCallBackUser->OnRecvData_TCPServer((BYTE*)info->m_recvBuf.buf, info->m_recvBuf.len, &info->m_cltInfo);
  810. GetLocalTime(&info->m_cltInfo.stLastActive);
  811. return true;
  812. }
  813. /*删除失效连接句柄*/
  814. bool TCPServerIOCP::DeleteLink(SOCKET s, char* strError)
  815. {
  816. m_csClientVectorLock.Lock();
  817. std::vector<COverlappedIOInfo*>::iterator iter = m_vecContInfo.begin();
  818. bool found = false;//标志位,客户端在列表中找到与否
  819. for (; iter != m_vecContInfo.end(); ++iter)
  820. {
  821. if ((*iter) && s == (*iter)->m_socket)
  822. {
  823. if (m_mapConnHistory.find((*iter)->m_cltInfo.strIP) != m_mapConnHistory.end()) {
  824. m_mapConnHistory[(*iter)->m_cltInfo.strIP]->Lock();
  825. m_mapConnHistory[(*iter)->m_cltInfo.strIP]->bOnline = false;
  826. m_mapConnHistory[(*iter)->m_cltInfo.strIP]->pCltInfo = NULL;
  827. m_mapConnHistory[(*iter)->m_cltInfo.strIP]->Unlock();
  828. }
  829. COverlappedIOInfo* ol = *iter;
  830. if (m_callBackTcpLog != nullptr)
  831. {
  832. m_callBackTcpLog(2, ol->m_cltInfo.strIP, ol->m_cltInfo.iPort, strError, 0, 0, 1);
  833. }
  834. m_pCallBackUser->ConnStatusChange(&ol->m_cltInfo, FALSE);
  835. closesocket(s);
  836. m_vecContInfo.erase(iter);
  837. if (ol)//避免重复删除
  838. {
  839. //delete ol;
  840. //ol = NULL;
  841. m_csCacheListLock.Lock();
  842. m_listContInfo.push_back({ std::shared_ptr<COverlappedIOInfo>(ol), GetTickCount() });
  843. m_csCacheListLock.Unlock();
  844. }
  845. found = true;//找到了
  846. break;
  847. }
  848. }
  849. if (!found)//客户端在列表中没有找到
  850. {
  851. }
  852. m_csClientVectorLock.Unlock();
  853. return true;
  854. }
  855. BOOL TCPServerIOCP::IsIPOnline(CString strIP)
  856. {
  857. m_csClientVectorLock.Lock();
  858. std::vector<COverlappedIOInfo*>::iterator iter = m_vecContInfo.begin();
  859. BOOL found = FALSE;//标志位,客户端在列表中找到与否
  860. for (; iter != m_vecContInfo.end(); ++iter)
  861. {
  862. if (strIP == (*iter)->m_cltInfo.strIP)
  863. {
  864. found = TRUE;//找到了
  865. break;
  866. }
  867. }
  868. m_csClientVectorLock.Unlock();
  869. return found;
  870. }
  871. /*关闭服务器*/
  872. void TCPServerIOCP::CloseServer()
  873. {
  874. //1.清空IOCP线程队列,退出工作线程,给所有的线程发送PostQueueCompletionStatus信息
  875. if (false == m_iocp.PostStatus(TYPE_CLOSE))
  876. {
  877. }
  878. //3.清空已连接的套接字m_vecContInfo并清空缓存
  879. for (int i = 0; i < m_vecContInfo.size(); i++)
  880. {
  881. COverlappedIOInfo* olinfo = m_vecContInfo.at(i);
  882. closesocket(olinfo->m_socket);
  883. if (m_callBackTcpLog != nullptr)
  884. {
  885. m_callBackTcpLog(2, olinfo->m_cltInfo.strIP, olinfo->m_cltInfo.iPort, "关闭服务器连接断开", 0, 0, 1);
  886. }
  887. delete olinfo;
  888. }
  889. m_vecContInfo.clear();
  890. }
  891. int TCPServerIOCP::StaticConnData(CString strIp, const char* data, int iLen, ConnDataWay way)
  892. {
  893. //if (strIp == GetMonitoring() && m_mapConnHistory.find(strIp) != m_mapConnHistory.end()) {
  894. // HWND hWnd = FindWindow(NULL, TCPIOCP_MANAGER);
  895. // if (hWnd) {
  896. // ConnDataNode* node = new ConnDataNode;
  897. // ::GetLocalTime(&node->time);
  898. // node->data = new char[iLen];
  899. // memcpy(node->data, data, iLen);
  900. // node->iDataLen = iLen;
  901. // node->way = way;
  902. // PostMessage(hWnd, UPDATE_ONE_DATA, (WPARAM)this, (LPARAM)node);
  903. // }
  904. //}
  905. return 0;
  906. }
  907. void TCPServerIOCP::ClearConnHistoryInfo()
  908. {
  909. for (auto it = m_mapConnHistory.begin(); it != m_mapConnHistory.end(); it++) {
  910. it->second->Lock();
  911. it->second->iSendSucCount = it->second->iSendFailCount = it->second->iReconnnectCount = it->second->iRecvCount = 0;
  912. it->second->Unlock();
  913. }
  914. }
  915. //获取IP列表
  916. void TCPServerIOCP::GetIPList(std::vector<CString> &vec)
  917. {
  918. m_csClientVectorLock.Lock();
  919. for (int i = 0; i < m_vecContInfo.size(); i++)
  920. {
  921. CString str = m_vecContInfo.at(i)->m_cltInfo.strIP;
  922. vec.push_back(str);
  923. }
  924. m_csClientVectorLock.Unlock();
  925. }
  926. void TCPServerIOCP::GetConnectInfo(std::vector<ClientInfo *> &vec)
  927. {
  928. m_csClientVectorLock.Lock();
  929. for (int i = 0; i < m_vecContInfo.size(); i++)
  930. {
  931. vec.push_back(&m_vecContInfo.at(i)->m_cltInfo);
  932. }
  933. m_csClientVectorLock.Unlock();
  934. }