本文介绍了c ++ tcp IP消息多线程编程响应慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在使用VC ++ MFC进行编程,以及我需要使用TCP / IP 消息接受5个连接。 但如果我为每个连接创建新线程我的软件将非常慢,甚至无法运行。但如果保持附加状态,每个命令响应时间仍然超过1秒左右,因为这是软件的一部分,所有其他模块都受到影响,整个软件扫描时间相当长。你可以帮帮我吗?这是代码。 UINT CMSELCtrl :: ThreadProc(LPVOID pParam) { CMSELCtrl * ctrl =(CMSELCtrl *)pParam; //设置状态当流程正在运行时, ctrl-> m_bThreadAlive = TRUE; //开始循环 HANDLE shutdownevent = ctrl - > m_hShutdownEvent; BOOL bAgain = TRUE; DWORD dwLoopInterval = ctrl-> m_dwLoopInterval; //以毫秒为单位 int m = 0; do $ { //等待通知。 if(WaitForSingleObject(ctrl-> m_hShutdownEvent,dwLoopInterval)== WAIT_OBJECT_0) { //主机请求关闭,清理内部和退出循环 bAgain = FALSE; //继续; break; } / /连接到控制器 for(int i = 0;我< MAX_MSELNO; i ++) { if(!m_AxisCtrl [i] .IsConnected()) { if((m_AxisCtrl [i] .m_strHostAddress1.GetLength()> 4)&&( m_AxisCtrl [i] .m_dwHostPort1> 0)) { //防止泛滥服务器 // if((m_AxisCtrl [i] .m_strClientAddress [0]> 0) &&(m_AxisCtrl [i] .m_dwClientPort> 0)) m_AxisCtrl [i] .ConnectToHost(m_AxisCtrl [i ] .m_strClientAddress,m_AxisCtrl [i] .m_dwClientPort); //(m_AxisCtrl [i] .m_strHostAddress1,m_AxisCtrl [i] .m_dwHostPort1,m_AxisCtrl [i] .m_strClientAddress,m_AxisCtrl [i] .m_dwClientPort); } } } //用于CAsyncSocket的泵消息 MSG消息; while(PeekMessage(& msg,NULL,0,0,PM_REMOVE)) { TranslateMessage(& msg); DispatchMessage(& msg); } } while(bAgain); //关闭套接字 for(int i = 0;我< MAX_MSELNO; i ++) { int nerrcode; m_AxisCtrl [i] .OnClose(nerrcode); } //设置状态为流程结束 ctrl-> m_bThreadAlive = FALSE; 返回TRUE; }UINT CMSELCtrl::ThreadProc(LPVOID pParam){CMSELCtrl *ctrl = (CMSELCtrl *)pParam;// set status as process is runningctrl->m_bThreadAlive = TRUE;// start loopHANDLE shutdownevent = ctrl->m_hShutdownEvent;BOOL bAgain = TRUE;DWORD dwLoopInterval = ctrl->m_dwLoopInterval;// in millisecondsint m = 0;do{ // Wait for notification.if (WaitForSingleObject(ctrl->m_hShutdownEvent, dwLoopInterval)==WAIT_OBJECT_0){ // host requested shutdown, cleanup internal and exit loopbAgain = FALSE;//continue;break;}// connect to Controllersfor (int i = 0; i <MAX_MSELNO; i++){if (!m_AxisCtrl[i].IsConnected()){if ((m_AxisCtrl[i].m_strHostAddress1.GetLength() > 4) && (m_AxisCtrl[i].m_dwHostPort1 > 0)){ // prevent flooding the server//if ((m_AxisCtrl[i].m_strClientAddress[0] > 0) && (m_AxisCtrl[i].m_dwClientPort > 0))m_AxisCtrl[i].ConnectToHost(m_AxisCtrl[i].m_strClientAddress, m_AxisCtrl[i].m_dwClientPort);//(m_AxisCtrl[i].m_strHostAddress1, m_AxisCtrl[i].m_dwHostPort1, m_AxisCtrl[i].m_strClientAddress, m_AxisCtrl[i].m_dwClientPort);}}}// pump message for CAsyncSocketMSG msg;while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){ TranslateMessage(&msg);DispatchMessage(&msg);}} while (bAgain);// close socketfor (int i = 0; i < MAX_MSELNO; i++){int nerrcode;m_AxisCtrl[i].OnClose(nerrcode);}// set status as process has ended ctrl->m_bThreadAlive = FALSE;return TRUE;} / * ======= ================================================== ======== * / b OOL CIAIAxisCtrl :: ConnectToHost(LPCTSTR sztempAddress,UINT utempPort)// LPCTSTR szHostAddress,UINT uHostPort,LPCTSTR szClientAddress,UINT uClientPort) { WSADATA wsaData; int iResult; // SOCKET sock,client; int errcode; addr.sin_family = AF_INET; // addr.sin_port = htons(uHostPort); //(44818); // addr.sin_addr.S_un.S_addr = inet_addr (szHostAddress); //(" 192.168.3.10"); addr.sin_port = htons(m_dwHostPort1); addr.sin_addr.S_un.S_addr = inet_addr(m_strHostAddress1); 尝试 { iResult = WSAStartup(MAKEWORD(2,2),& wsaData); if(iResult) { DEBUG_PRINT(LPCTSTR("WSA startup failed")); 返回FALSE; } } catch(int ex ) { DEBUG_PRINT("发生异常。例外Nr。 %u",ex); } 尝试 { ListenSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); / * LONG lEventa = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE; ListenSocket.Create(addr.sin_port,SOCK_STREAM,lEventa); * / if(ListenSocket == INVALID_SOCKET) { DEBUG_PRINT(LPCTSTR("无效套接字")); closesocket(ListenSocket); 返回FALSE; } } catch(int ex) { DEBUG_PRINT("发生异常。例外Nr。%u",ex); } 试试 { iResult = bind(ListenSocket,(sockaddr *)& addr,sizeof(sockaddr_in)); // iResult = ListenSocket.Bind((sockaddr *)& addr,sizeof(sockaddr_in)); if(iResult) { errcode = GetLastError() ; DEBUG_PRINT(" bind failed%u",GetLastError()); closesocket(ListenSocket); WSACleanup(); 返回FALSE; } } catch( int ex) { DEBUG_PRINT("发生异常。例外Nr。 %u",ex); } 尝试 { iResult = listen(ListenSocket,SOMAXCONN); // iResult = ListenSocket.Listen(); if(iResult) { errcode = GetLastError(); DEBUG_PRINT(" iResult failed%u",GetLastError()); closesocket(ListenSocket); WSACleanup(); return FALSE; } } catch(int ex) { DEBUG_PRINT("发生异常。例外Nr。 %u",ex); } cliendaddr.sin_family = AF_INET; // cliendaddr.sin_port = htons(uClientPort); //( 64511); $ // cliendaddr.sin_addr.S_un.S_addr = inet_addr(szClientAddress); //(" 192.168.3.32 "); / * cliendaddr.sin_port = htons(m_dwClientPort); cliendaddr.sin_addr.S_un.S_addr = inet_addr(m_strClientAddress); * / clientaddlen = sizeof(cliendaddr); DWORD线程; // tempaddr.sin_family = AF_INET; //// cliendaddr.sin_port = htons(uClientPort); //(64511); //// cliendaddr.sin_addr.S_un.S_add r = inet_addr(szClientAddress); //(" 192.168.3.32"); // tempaddr.sin_port = htons (m_dwClientPort); // utempPort); // tempaddr.sin_addr.S_un.S_addr = inet_addr(m_strClientAddress); // sztempAddress); tempaddlen = sizeof(tempaddr); char ipstr [16]; INT nSocketType = SOCK_STREAM; // LONG lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE; LONG lEvent = FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE; // if(ClientSocket == INVALID_SOCKET)//(m_hSocket == INVALID_SOCKET) // { //如果没有创建则创建 // if(!ClientSocket.Create(tempaddr.sin_port,nSocketType,lEvent)) // { //错误情况 // INT nCode = GetLastError(); // CString strError; // strError.Format(_T("InfoServer::ConnectToHost - 创建错误:%08X \ n%s"),nCode,GetErrorMessage(nCode)); // DEBUG_PRINT(LPCTSTR(strError)); // closesocket(ListenSocket); // WSACleanup(); // 返回FALSE; // } //} // while(true) while(! m_bConnected) { 尝试 { m_hSocket = accept(ListenSocket,(sockaddr *)& cliendaddr,& clientaddlen); // ListenSocket.Accept(ClientSocket); // accept(ListenSocket,(sockaddr *)& cliendaddr,& clientaddlen); if(m_hSocket == INVALID_SOCKET) { DEBUG_PRINT(LPCTSTR("无效套接字")); closesocket(ListenSocket); 返回FALSE; { inet_ntop(PF_INET,& cliendaddr.sin_addr,_T(m_strClientAddress),INET_ADDRSTRLEN); ClientSocket.Attach(m_hSocket,lEvent); $ getpeername(ClientSocket,(sockaddr *)& tempaddr1,& tempaddlen1); sockaddr_in * saddtemp =(sockaddr_in * )& tempaddr1; int nport = ntohs(saddtemp-> sin_port); inet_ntop(AF_INET,& saddtemp-> sin_addr,ipstr,sizeof(ipstr)); // m_strMessage = NULL_STRING; closesocket(ListenSocket); m_bConnected = TRUE; // Start( ); $ DEBUG_PRINT(" Client connected\r\ n"); g_DataLog.WriteLog2(LPCTSTR(m_strAxisName1),_ T(&*** *** Connected")); 返回TRUE; } // CreateThread(NULL,0,OnReceive,(LPVOID)client,0,& thread); } catch(int ex) { DEBUG_PRINT(" ;发生了异常。例外Nr。 %u",ex); } if(ClientSocket == INVALID_SOCKET) { errcode = GetLastError(); m_bConnected = FALSE; DEBUG_PRINT("接受失败,错误%u",GetLastError()); closesocket(ListenSocket); WSACleanup(); 返回FALSE; } } closesocket(ListenSocket); 返回FALSE; }/* ================================================================= */BOOL CIAIAxisCtrl::ConnectToHost(LPCTSTR sztempAddress, UINT utempPort)//LPCTSTR szHostAddress, UINT uHostPort, LPCTSTR szClientAddress, UINT uClientPort){WSADATA wsaData;int iResult;//SOCKET sock, client;int errcode;addr.sin_family = AF_INET;//addr.sin_port = htons(uHostPort);//(44818);//addr.sin_addr.S_un.S_addr = inet_addr(szHostAddress);//("192.168.3.10");addr.sin_port = htons(m_dwHostPort1);addr.sin_addr.S_un.S_addr = inet_addr(m_strHostAddress1);try{iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);if (iResult){DEBUG_PRINT(LPCTSTR("WSA startup failed"));return FALSE;}}catch (int ex){DEBUG_PRINT("An exception occurred. Exception Nr. %u", ex);}try{ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);/*LONG lEventa = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE;ListenSocket.Create(addr.sin_port, SOCK_STREAM, lEventa);*/if (ListenSocket == INVALID_SOCKET){DEBUG_PRINT(LPCTSTR("Invalid socket"));closesocket(ListenSocket);return FALSE;}}catch (int ex){DEBUG_PRINT("An exception occurred. Exception Nr. %u", ex);}try{iResult = bind(ListenSocket, (sockaddr*)&addr, sizeof(sockaddr_in));//iResult = ListenSocket.Bind((sockaddr*)&addr, sizeof(sockaddr_in));if (iResult){errcode = GetLastError();DEBUG_PRINT("bind failed %u", GetLastError());closesocket(ListenSocket);WSACleanup();return FALSE;}}catch (int ex){DEBUG_PRINT("An exception occurred. Exception Nr. %u", ex);}try{iResult = listen(ListenSocket, SOMAXCONN);//iResult = ListenSocket.Listen();if (iResult){errcode = GetLastError();DEBUG_PRINT("iResult failed %u", GetLastError());closesocket(ListenSocket);WSACleanup();return FALSE;}}catch (int ex){DEBUG_PRINT("An exception occurred. Exception Nr. %u", ex);}cliendaddr.sin_family = AF_INET;//cliendaddr.sin_port = htons(uClientPort);//(64511);//cliendaddr.sin_addr.S_un.S_addr = inet_addr(szClientAddress);//("192.168.3.32");/*cliendaddr.sin_port = htons(m_dwClientPort);cliendaddr.sin_addr.S_un.S_addr = inet_addr(m_strClientAddress);*/clientaddlen = sizeof(cliendaddr);DWORD thread;//tempaddr.sin_family = AF_INET;////cliendaddr.sin_port = htons(uClientPort);//(64511);////cliendaddr.sin_addr.S_un.S_addr = inet_addr(szClientAddress);//("192.168.3.32");//tempaddr.sin_port = htons(m_dwClientPort);//utempPort);//tempaddr.sin_addr.S_un.S_addr = inet_addr(m_strClientAddress);//sztempAddress);tempaddlen = sizeof(tempaddr);char ipstr[16];INT nSocketType = SOCK_STREAM;// LONG lEvent = FD_READ | FD_WRITE | FD_OOB | FD_ACCEPT | FD_CONNECT | FD_CLOSE;LONG lEvent = FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE;//if (ClientSocket == INVALID_SOCKET)// (m_hSocket == INVALID_SOCKET)//{ // create if not created// if (!ClientSocket.Create(tempaddr.sin_port, nSocketType, lEvent))// {// error condition// INT nCode = GetLastError();// CString strError;// strError.Format(_T("InfoServer::ConnectToHost - Create error: %08X\n%s"), nCode, GetErrorMessage(nCode));// DEBUG_PRINT(LPCTSTR(strError));// closesocket(ListenSocket);// WSACleanup();// return FALSE;// }//}//while (true)while (!m_bConnected){try{m_hSocket = accept(ListenSocket, (sockaddr*)&cliendaddr, &clientaddlen);//ListenSocket.Accept(ClientSocket);// accept(ListenSocket, (sockaddr*)&cliendaddr, &clientaddlen);if (m_hSocket == INVALID_SOCKET){DEBUG_PRINT(LPCTSTR("Invalid socket"));closesocket(ListenSocket);return FALSE;}if (m_hSocket){inet_ntop(PF_INET, &cliendaddr.sin_addr, _T(m_strClientAddress),INET_ADDRSTRLEN);ClientSocket.Attach(m_hSocket, lEvent);getpeername(ClientSocket, (sockaddr*)&tempaddr1, &tempaddlen1);sockaddr_in *saddtemp = (sockaddr_in *)&tempaddr1;int nport = ntohs(saddtemp->sin_port);inet_ntop(AF_INET, &saddtemp->sin_addr, ipstr, sizeof(ipstr));//m_strMessage = NULL_STRING;closesocket(ListenSocket);m_bConnected = TRUE;//Start();DEBUG_PRINT("Client connected\r\n");g_DataLog.WriteLog2(LPCTSTR(m_strAxisName1), _T("*** Connected"));return TRUE;}//CreateThread(NULL, 0, OnReceive, (LPVOID)client, 0, &thread);}catch (int ex){DEBUG_PRINT("An exception occurred. Exception Nr. %u", ex);}if (ClientSocket == INVALID_SOCKET){errcode = GetLastError();m_bConnected = FALSE;DEBUG_PRINT("accept failed with error %u", GetLastError());closesocket(ListenSocket);WSACleanup();return FALSE;}}closesocket(ListenSocket);return FALSE;}推荐答案感谢您在此处发帖。 >> c ++ tcp IP消息多线程编程响应缓慢 &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;>>c++ tcp IP message multithread programming response slow 您是否检查了关键部分的锁定状态?Have you checked the lock states of the critical section?这是一份可以帮助您提高性能的文档套接字编程。你可以参考它。Here is a document which could help you improve the performance of the socket programming. You could refer to it. https://msdn.microsoft.com/en-us/library/windows/desktop/ms738559(v = vs.85).aspx另请参阅下面的本文档中的多线程信息。Also refer to the multi thread information in this document below. https://msdn.microsoft.com/en-us/library/windows/desktop/ms738545%28v=vs.85%29.aspx? f = 255& MSPPError = -2147217396希望这可以帮到你。最好的问候, Baron Bi 这篇关于c ++ tcp IP消息多线程编程响应慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 06-24 11:36