dword ClientTask() { CScopedLock _lock; CTcpClient* pClient = NULL; CDataDoubleLinkedListT<CTcpClient>::Iterator it = _tcpclients.Begin(); if ( it && (*it) ) { pClient = *it; _tcpclients.Remove(it, EmptyDeleteFunc, NULL); } if ( !pClient ) return 0; CStringBuffer sBuffer; wcout(_T("ClientTask")); try { CStringConstIterator itB; bool bExit = false; _lock.unlock(); ReceiveData(pClient, sBuffer); wcout(sBuffer.GetString()); SendData(pClient, sBuffer); ReceiveData(pClient, sBuffer); wcout(sBuffer.GetString()); SendData(pClient, sBuffer); ReceiveData(pClient, sBuffer); wcout(sBuffer.GetString()); SendData(pClient, sBuffer); ReceiveData(pClient, sBuffer); wcout(sBuffer.GetString()); SendData(pClient, sBuffer); ReceiveData(pClient, sBuffer); itB = sBuffer; itB.Find(_T("STOP\r\n")); if ( itB.IsBegin() ) bExit = true; wcout(sBuffer.GetString()); SendData(pClient, sBuffer); pClient->CloseConnection(); _lock.lock(); pClient->release(); _bExit = bExit; } catch ( CTcpClientException* ex ) { COUT << ex->GetExceptionMessage() << endl; pClient->CloseConnection(); } return 0; }
bool ScutDataLogic::CDataRequest::ExecTcpRequest(CDataHandler* pHandler, const char* lpszUrl, const char* lpSendData, unsigned int nDataLen) { if (pHandler) { if (m_pTcpClient == NULL) { m_pTcpClient = new CTcpClient(); } if (nDataLen == 0) { nDataLen = strlen(lpSendData); } CHttpClientResponse resp; resp.SetTarget(new CMemoryStream()); resp.SetSendData(lpSendData, nDataLen); if (!m_pTcpClient->IsBusy()) { //直接执行同步请求 if (m_pTcpClient->TcpGet(lpszUrl, resp) == 0) //成功 { //在此判断是否存在 if (pHandler && pHandler->IsAlive()) { return pHandler->HandleData(0, *resp.GetTarget(), NULL); } } } else { CTcpClient* pTcpClient = new CTcpClient(); if (pTcpClient) { //直接执行同步请求 if (pTcpClient->TcpGet(lpszUrl, resp) == 0) //成功 { //在此判断是否存在 if (pHandler && pHandler->IsAlive()) { return pHandler->HandleData(0, *resp.GetTarget(), NULL); } } } } } return false; }
void TestTCPClientKeepAlive(CStringLiteral command) { CTcpClient tcpClient; CStringBuffer sBuffer; CStringBuffer sBuffer0(__FILE__LINE__ _T("10: Testdaten (Client): 0123456789")); CStringBuffer sBuffer1(__FILE__LINE__ _T("20: Testdaten (Client): 0123456789")); CStringBuffer sBuffer2(__FILE__LINE__ _T("30: Testdaten (Client): 0123456789")); CStringBuffer sBuffer3(__FILE__LINE__ _T("40: Testdaten (Client): 0123456789")); CStringBuffer sBuffer4(__FILE__LINE__ _T("50: Testdaten (Client): 0123456789")); try { tcpClient.OpenConnection(_T("localhost"), DEFAULT_PORT); TestTCPClientKeepAlive_SendData(tcpClient, sBuffer0); TestTCPClientKeepAlive_ReceiveData(tcpClient, sBuffer); COUT << sBuffer << endl; TestTCPClientKeepAlive_SendData(tcpClient, sBuffer1); TestTCPClientKeepAlive_ReceiveData(tcpClient, sBuffer); COUT << sBuffer << endl; TestTCPClientKeepAlive_SendData(tcpClient, sBuffer2); TestTCPClientKeepAlive_ReceiveData(tcpClient, sBuffer); COUT << sBuffer << endl; TestTCPClientKeepAlive_SendData(tcpClient, sBuffer3); TestTCPClientKeepAlive_ReceiveData(tcpClient, sBuffer); COUT << sBuffer << endl; sBuffer.Clear(); if ( !!command ) { COUT << command << endl; sBuffer.AppendString(command); sBuffer.AppendString(_T("\r\n")); } sBuffer.AppendString(sBuffer4); TestTCPClientKeepAlive_SendData(tcpClient, sBuffer); TestTCPClientKeepAlive_ReceiveData(tcpClient, sBuffer); COUT << sBuffer << endl; tcpClient.CloseConnection(); } catch ( CTcpClientException* ex ) { COUT << ex->GetExceptionMessage() << endl; tcpClient.CloseConnection(); } }
static void TestTCPClientKeepAlive_SendData(CTcpClient& tcpClient, const CStringBuffer& buffer) { CStringBuffer sBuffer; CByteBuffer bBuffer; dword numBytesSend; sBuffer.FormatString(__FILE__LINE__ _T("##%05d## %s"), buffer.GetLength(), buffer.GetString()); sBuffer.convertToByteBuffer(bBuffer); tcpClient.SendData(bBuffer.get_Buffer(), bBuffer.get_BufferSize(), &numBytesSend); assert(numBytesSend == bBuffer.get_BufferSize()); }
void CTestTcpIpMultiServer::CTestConnection::runTest() { CFileLog::cfilelog() << "---" << std::endl; CFileLog::cfilelog() << "CTestTcpIpMultiServer::CTestConnection started" << std::endl; CTcpServerManager serverMgr; CTcpConnectionListener listener; listener.setListenerFunctions( CTestTcpIpMultiServer::DoReceive, CTestTcpIpMultiServer::DoConnect, CTestTcpIpMultiServer::DoDisconnect); serverMgr.createServer("127.0.0.1", 20500, listener); unique_lock<mutex> lock(s_mutex); CTcpClient* client = CTcpClient::clientFactory("127.0.0.1", 20500); boost::thread clientThr(&CTcpClient::startClient, client); if (s_connect.do_wait_for(lock, {10,0}) == true) { CPPUNIT_ASSERT_EQUAL_MESSAGE("CTestTcpIpMultiServer::CTestConnection WRONG", true, client->is_connected()); this_thread::sleep(posix_time::microseconds(500)); } else { CPPUNIT_ASSERT_EQUAL_MESSAGE("CTestTcpIpMultiServer::CTestConnection timed out", 0, 1); } client->stop(); clientThr.join(); delete client; client.Disconnect(); }
UINT #else DWORD #endif WINAPI CTcpClient::WorkerThreadProc(LPVOID pv) { TRACE("---------------> Client Worker Thread 0x%08X started <---------------\n", ::GetCurrentThreadId()); CTcpClient* pClient = (CTcpClient*)pv; HANDLE hEvents[] = {pClient->m_evSocket, pClient->m_evBuffer, pClient->m_evWorker}; pClient->m_rcBuffer.Malloc(pClient->m_dwSocketBufferSize); while(pClient->HasStarted()) { DWORD retval = ::WSAWaitForMultipleEvents(3, hEvents, FALSE, WSA_INFINITE, FALSE); if(retval == WSA_WAIT_EVENT_0) { if(!pClient->ProcessNetworkEvent()) { if(pClient->HasStarted()) pClient->Stop(); break; } } else if(retval == WSA_WAIT_EVENT_0 + 1) { if(!pClient->SendData()) { if(pClient->HasStarted()) pClient->Stop(); break; } } else if(retval == WSA_WAIT_EVENT_0 + 2) break; else ASSERT(FALSE); } TRACE("---------------> Client Worker Thread 0x%08X stoped <---------------\n", ::GetCurrentThreadId()); return 0; }
static void TestTCPClientKeepAlive_ReceiveData(CTcpClient& tcpClient, CStringBuffer& buffer) { CStringBuffer responseString; CByteBuffer responseBuffer; dword numDataReceived = 0; dword totalDataReceived = 0; CStringConstIterator itB; CStringBuffer sBuffer; dword numData; for ( ; totalDataReceived < 10; ) { responseBuffer.set_BufferSize(__FILE__LINE__ totalDataReceived + MAX_BUFFER); tcpClient.ReceiveData(responseBuffer.get_Buffer() + totalDataReceived, MAX_BUFFER, &numDataReceived); totalDataReceived += numDataReceived; responseBuffer.set_BufferSize(__FILE__LINE__ totalDataReceived); } responseString.convertFromByteBuffer(responseBuffer); itB = responseString.GetString(); if ( (itB[0] == _T('#')) && (itB[1] == _T('#')) && (itB[7] == _T('#')) && (itB[8] == _T('#')) ) { responseString.SubString(2, 5, sBuffer); if ( sBuffer.ScanString(_T("%u"), &numData) <= 0 ) return; } else return; for ( ; totalDataReceived < (10 + numData); ) { responseBuffer.set_BufferSize(__FILE__LINE__ totalDataReceived + MAX_BUFFER); tcpClient.ReceiveData(responseBuffer.get_Buffer() + totalDataReceived, MAX_BUFFER, &numDataReceived); totalDataReceived += numDataReceived; responseBuffer.set_BufferSize(__FILE__LINE__ totalDataReceived); } responseString.convertFromByteBuffer(responseBuffer); responseString.SubString(10, numData, buffer); }
DWORD CTcpClient::ConnectThread(LPVOID lpParameter) { CTcpClient* pTcp = (CTcpClient*)lpParameter; if (pTcp == NULL) return false; pTcp->m_bConnecting = true; // Initialize WinSock 2 WSADATA wsaData; OutputDebugString("Initializing WinSock..."); int wsaret = WSAStartup(0x101, &wsaData); if (wsaret) { pTcp->m_bConnecting = false; pTcp->m_MsgCallBack("<LOG>Unable to connect to TCP server: Unable to initialize Winsock.\n</LOG>", pTcp->m_lParam); return false; } // Create the TCP socket as a stream SOCKET winSock; winSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (winSock == INVALID_SOCKET) { pTcp->m_bConnecting = false; pTcp->m_MsgCallBack("<LOG>Unable to connect to TCP server: Unable to create socket.\n</LOG>", pTcp->m_lParam); return false; } OutputDebugString("Created socket..."); // Resolve the server host address hostent *hp; unsigned long addr; if (inet_addr(pTcp->m_strServer) == INADDR_NONE) { hp = gethostbyname(pTcp->m_strServer); } else { addr = inet_addr(pTcp->m_strServer); hp = gethostbyaddr((char*)&addr, sizeof(addr), AF_INET); } if (hp == NULL) { pTcp->m_bConnecting = false; pTcp->m_MsgCallBack("<LOG>Unable to connect to TCP server: Unable to resolve host.\n</LOG>", pTcp->m_lParam); return false; } char msgBuff[512]; // Create server's socket struct struct sockaddr_in server; server.sin_addr.s_addr=*((unsigned long*)hp->h_addr); server.sin_family=AF_INET; server.sin_port=htons(pTcp->m_wPort); // Connect to the TCP server if (connect(winSock, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) { int nError = WSAGetLastError(); if (nError == WSAECONNREFUSED) { sprintf(msgBuff, "<LOG>Failed to connect to TCP server: Connection refused due to no server running.\n</LOG>"); } else if (nError == WSAETIMEDOUT) { sprintf(msgBuff, "<LOG>Failed to connect to TCP server: Timeout trying to connect to server.\n</LOG>"); } else { sprintf(msgBuff, "<LOG>Failed to connect to TCP server: Error %d\n</LOG>", nError); } pTcp->m_bConnecting = false; closesocket(winSock); pTcp->m_MsgCallBack(msgBuff, pTcp->m_lParam); return false; } // Successfully connected pTcp->m_winSock = winSock; pTcp->m_bConnected = true; pTcp->m_bConnecting = false; sprintf(msgBuff, "<CONNECTED>Connected to TCP server on %s:%d.\n</CONNECTED>", pTcp->m_strServer, pTcp->m_wPort); pTcp->m_MsgCallBack(msgBuff, pTcp->m_lParam); int nBytes; CString strMessage = ""; do { // Receive until the server closes the connection or there is an error nBytes = 0; char buff[SOCKET_BUFF_SIZE] = { 0 }; nBytes = recv(pTcp->m_winSock, buff, SOCKET_BUFF_SIZE, 0); if (nBytes > 0) { // Got a packet...check if it is a full message if (buff[nBytes - 1] == '\0') { // Got a full message strMessage += buff; pTcp->m_MsgCallBack(strMessage, pTcp->m_lParam); OutputDebugString("Got a message from recv..."); strMessage = ""; } else { // got a partial message OutputDebugString("Got a partial message from recv..."); strMessage += buff; } } else if (nBytes == 0) { // close the connection pTcp->m_MsgCallBack("<LOG>Server has closed the connection.\n</LOG>", pTcp->m_lParam); } else { sprintf(msgBuff, "<LOG>TCP receive error: %d\n</LOG>", WSAGetLastError()); } } while (nBytes > 0); // cleanup closesocket(pTcp->m_winSock); WSACleanup(); pTcp->m_winSock = NULL; pTcp->m_bConnected = false; OutputDebugString("Client has disconnected..."); return 1; }
int main(int argc, char *argv[]) { if (argc < 3) { printf("Please set a host(like \"127.0.0.1\") and protocol(\"u\" or \"t\")\n"); return -1; } int port = 10889; struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = inet_addr(argv[1]); if (addr.sin_addr.s_addr == -1) { printf("Unknown address.\n"); return -1; } if (argv[2][0] != 'u' && argv[2][0] != 't') { printf("Unknown protocol. Should be \"u\" or \"t\".\n"); return -1; } CUdpClient udpClient; CTcpClient tcpClient; CClient *client; if (argv[2][0] == 'u') { udpClient.open(addr); client = &udpClient; } else { if (tcpClient.open(addr)) { printf("Connection error\n"); return -1; } client = &tcpClient; } for (;;) { cout << "input string: "; string msg; getline(cin, msg); string answ; if (client->sendMessage(msg, answ) < 0) { printf("Error while receiving of answer. Will exit.\n"); break; } cout << "Answer: " << answ << endl; } return 0; }
void CTestTcpIpMultiServer::CTestSendReceive::runTest() { CFileLog::cfilelog() << "---" << std::endl; CFileLog::cfilelog() << "CTestTcpIpMultiServer::CTestSendReceive started " << std::endl; CTcpServerManager serverMgr; CTcpConnectionListener listener; listener.setListenerFunctions( CTestTcpIpMultiServer::DoReceive, CTestTcpIpMultiServer::DoConnect, CTestTcpIpMultiServer::DoDisconnect); CTcpServer* server = serverMgr.createServer("127.0.0.1", 20500, listener); unique_lock<mutex> lock(s_mutex); CTcpClient* client = CTcpClient::clientFactory("127.0.0.1", 20500); boost::thread clientThr(&CTcpClient::startClient, client); if (s_connect.do_wait_for(lock, {5,0}) == true) { CPPUNIT_ASSERT_EQUAL_MESSAGE("CTestTcpIpMultiServer::CTestConnection WRONG", true, client->is_connected()); this_thread::sleep(posix_time::microseconds(500)); } else { CPPUNIT_ASSERT_EQUAL_MESSAGE("CTestTcpIpMultiServer::CTestConnection timed out", 0, 1); } { std::vector<uint8_t> expectedData; for (auto v: s_testData) expectedData.push_back(v); unique_lock<mutex> lockSendRcv(s_mutex2); boost::thread sendthr(send_message, client, expectedData); if (s_read.do_wait_for(lockSendRcv, {10,0} ) == false) { CPPUNIT_ASSERT_EQUAL_MESSAGE("CTestTcpIpMultiServer::CTestSendReceive wait data timed out", 0, 1); } sendthr.join(); CPPUNIT_ASSERT_EQUAL_MESSAGE("CTestTcpIpMultiServer::CTestSendReceive expected length != result length", expectedData.size(), CTestTcpIpMultiServer::s_resultData.size()); uint32_t size = expectedData.size(); for (uint32_t i = 0; i < size; ++i) { CPPUNIT_ASSERT_EQUAL_MESSAGE("CTestTcpIpMultiServer::CTestSendReceive receive data WRONG", expectedData[i], CTestTcpIpMultiServer::s_resultData[i]); } std::list<std::vector<uint8_t> > sendData; sendData.push_back(s_resultData); server->send(0, sendData); } client->stop(); clientThr.join(); delete client; }
static void __stdcall CTestTCPServerDeleteFunc( ConstPointer data, Pointer context ) { CTcpClient* pClient = CastAnyPtr(CTcpClient, CastMutable(Pointer, data)); pClient->release(); }