void TestClient::SendThread() { vector<ClientData*> clientList; UINT halfTick = m_InitData.Timeout >> 1; NetCmd nc; nc.SetCmdSize(sizeof(nc)); nc.SetCmdType(ConvertDWORDToWORD(m_InitData.CmdHearbeat)); long threadIdx = ::InterlockedIncrement(&m_SendIndex) - 1; SafeList<ClientData*> &sendList = m_NewSendList[threadIdx]; Timer t; t.Begin(); while (m_bRun) { while (sendList.HasItem()) clientList.push_back(sendList.GetItem()); UINT tick = GetTickCount(); for (UINT i = 0; i < clientList.size();) { ClientData *pc = clientList[i]; if (pc->InsideRemoved) { RemoveClient(pc); ListRemoveAt(clientList, i); continue; } if (tick - pc->SendTick > halfTick) { int nret = send(pc->Socket, (const char*)&nc, nc.CmdSize, 0); if (nret != nc.CmdSize) { Log(L"send hearbeat err:%d, lastErr:%d", nret, WSAGetLastError()); } pc->SendTick = tick; } ++i; } m_SendData[threadIdx].Num = clientList.size(); m_SendData[threadIdx].Delta = t.Intecept(); Sleep(m_InitData.SleepTime); } for (UINT i = 0; i < clientList.size(); ++i) RemoveClient(clientList[i]); ::InterlockedIncrement(&m_ExitCount); }
void TestClient::RecvThread() { fd_set *pSet = CreateFDSet(); timeval time = { 0, 0 }; vector<ClientData*> recvList; long threadIdx = ::InterlockedIncrement(&m_RecvIndex) - 1; SafeList<ClientData*> &recvNewList = m_NewRecvList[threadIdx]; Timer t; t.Begin(); while (m_bRun) { while (recvNewList.HasItem()) { recvList.push_back(recvNewList.GetItem()); } FD_ZERO(pSet); UINT tick = GetTickCount(); uint idx = 0; for (; idx < recvList.size();) { ClientData *pscd = recvList[idx]; if (pscd->InsideRemoved || tick - pscd->RecvTick > m_InitData.Timeout) { if (tick - pscd->RecvTick > m_InitData.Timeout) Log(L"Timeout:%d", tick - pscd->RecvTick); RemoveClient(pscd); ListRemoveAt(recvList, idx); continue; } FD_ADD(pscd->Socket, pSet); ++idx; } if (idx > 0) { int nRet = select(0, pSet, NULL, NULL, &time); if (nRet != 0) for (uint i = 0; i < recvList.size(); ++i) { ClientData *pscd = recvList[i]; if (!FD_ISSET(pscd->Socket, pSet)) continue; int curPos = pscd->Offset + pscd->RecvSize; nRet = recv(pscd->Socket, (char*)pscd->Buff + curPos, m_InitData.BuffSize - curPos, 0); if (nRet == 0 || (nRet == SOCKET_ERROR && (WSAGetLastError() == WSAECONNRESET || WSAGetLastError() == WSAECONNABORTED))) { Log(L"recv error:%d, LastCode:%d", nRet, WSAGetLastError()); pscd->InsideRemoved = true; } else if (!RecvData(pscd, nRet)) { Log(L"recv size error:%d, LastCode:%d", nRet, WSAGetLastError()); pscd->InsideRemoved = true; } else { while (pscd->RecvList.HasItem()) { free(pscd->RecvList.GetItem()); } pscd->RecvTick = tick; } }// end for }//enf if m_RecvData[threadIdx].Num = recvList.size(); m_RecvData[threadIdx].Delta = t.Intecept(); Sleep(m_InitData.SleepTime); } for (UINT i = 0; i < recvList.size(); ++i) RemoveClient(recvList[i]); DeleteFDSet(pSet); ::InterlockedIncrement(&m_ExitCount); }