BOOL KLogClient::Connect() { BOOL bResult = false; BOOL bRetCode = false; KG_SocketConnector Connector; struct timeval TimeVal; IKG_SocketStream* piSocketStream = NULL; IKG_Buffer* piPackage = NULL; G2L_HANDSHAKE_REQUEST* pHandshake = NULL; piSocketStream = Connector.Connect(m_szLogServerAddr, m_nRelayPort); KG_PROCESS_ERROR(piSocketStream); TimeVal.tv_sec = 0; TimeVal.tv_usec = 10000; bRetCode = piSocketStream->SetTimeout(&TimeVal); KGLOG_PROCESS_ERROR(bRetCode); m_bSocketError = false; //m_nWorldIndex = 0; m_nLastSendPacketTime = g_pSO3World->m_nCurrentTime; // 初始化的一些操作,注意多线程 piPackage = KG_MemoryCreateBuffer((unsigned)sizeof(G2L_HANDSHAKE_REQUEST)); KGLOG_PROCESS_ERROR(piPackage); pHandshake = (G2L_HANDSHAKE_REQUEST*)piPackage->GetData(); KGLOG_PROCESS_ERROR(pHandshake); pHandshake->wProtocolID = g2l_handshake_request; pHandshake->nServerTime = (int)time(NULL); pHandshake->nServerIndexInGC = g_pSO3World->m_nServerIndexInGC; bRetCode = piSocketStream->Send(piPackage); KGLOG_PROCESS_ERROR(bRetCode == 1); // 小心: 这里不能写成 "m_piSocket = piSocket; m_piSocket->AddRef(); ", 那样会导致线程安全隐患 piSocketStream->AddRef(); m_piSocketStream = piSocketStream; KGLogPrintf( KGLOG_INFO, "Connect to log server %s:%d ... ... [OK]", m_szLogServerAddr, m_nRelayPort ); bResult = true; Exit0: KG_COM_RELEASE(piPackage); KG_COM_RELEASE(piSocketStream); return bResult; }
int KClient::SendPackToServer(unsigned int uLinkId, const void *pData, unsigned int uLen) { ASSERT(pData && uLen); int nRet = guard_err; do { if (uLinkId >= (unsigned int)m_nMaxConnCount) { ASSERT(FALSE); break; } IKG_SocketStream* pConnection = m_ppConnections[uLinkId]; if (!pConnection) { // ASSERT(FALSE); break; } IKG_Buffer *pBuffer = KG_MemoryCreateBuffer(uLen); if (!pBuffer) { ASSERT(FALSE); break; } memcpy(pBuffer->GetData(), pData, uLen); INT nResult = pConnection->Send(pBuffer); pBuffer->Release(); if (nResult != 1) { OnConnectionClose(uLinkId); pConnection->Release(); break; } nRet = fseye_success; } while(0); return nRet; }