void CComplSocketClient::DealCache(const CString& msg)
{
	if(msg.IsEmpty() || IsTheSameMsg(msg))return;
	theApp.m_list_caCheMsg.push_back(msg);
#ifdef _DEBUG
	CString str=_T("cache size:");
	str.AppendFormat(_T("%d"),theApp.m_list_caCheMsg.size());
	MyWriteConsole(str);
#endif
	if(theApp.m_list_caCheMsg.size()>=10)
	{
		CFile file;
		if(file.Open(m_caChePath,CFile::modeCreate | CFile::modeNoTruncate |CFile::modeWrite))
		{
			std::list<CString>::const_iterator itera = theApp.m_list_caCheMsg.begin();
			for(itera;itera!=theApp.m_list_caCheMsg.end();itera++)
			{
				file.SeekToEnd();
				CString temp = *itera;
				char tempBuf[MAXRECVBUF] ={0};
				CCommonConvert::CStringToChar(temp,tempBuf);
				file.Write(tempBuf,MAXRECVBUF);
			}
			theApp.m_list_caCheMsg.clear();//清除缓存
			file.Close();
		}
	}
}
Exemplo n.º 2
0
DWORD WINAPI SLZCWndScreen::DoThrWndMsgThread(LPVOID pParam)
{
	SLZCWndScreen* pThis = (SLZCWndScreen*)pParam;
	while(TRUE)
	{
		if(pThis->m_list_sendThrMsg.empty())
		{
			Sleep(5);
		}
		else
		{
			SendThrScreenMsg msg;
			pThis->m_ThrWndMutex.Lock();
			std::list<SendThrScreenMsg>::const_iterator itera = pThis->m_list_sendThrMsg.begin();
			msg = *itera;
			pThis->m_list_sendThrMsg.pop_front();
			pThis->m_ThrWndMutex.Unlock();
//			WaitForSingleObject(pThis->m_hDoWndScreenMsgThread,3);
#ifdef _DEBUG
			CString strAddress;
			strAddress.Format(_T("%d"),msg.address);
			CString strChannel;
			strChannel.Format(_T("%d"),msg.channel);

			MyWriteConsole(_T("通屏信息:") + msg.msg + _T("地址:") + strAddress + _T("通道:") + strChannel + _T("ip:") + msg.localIp );
#endif
			pThis->SendDataToThroughScreen(msg.msg,msg.address,msg.channel,msg.localIp);
		}
	}
	return 0;
}
Exemplo n.º 3
0
int CProducePacket::JudgePacketRet(const std::string strPacket)
{
	CWriteLogError writeLogErr;
	if(strPacket.empty())
	{
		writeLogErr.WriteErrLog(_T("返回报文为空"));
		return -1;
	}
	CString wRecvMsg(strPacket.c_str());
	CString wFormatRecvMsg = _T("recvSwingCardMsg:") + wRecvMsg;
#ifdef _DEBUG
	MyWriteConsole(wRecvMsg);
#endif
	std::string::size_type firstIndex = strPacket.find("<retCode>");
	if(firstIndex == strPacket.npos)
	{
		writeLogErr.WriteErrLog(wFormatRecvMsg);
		writeLogErr.WriteErrLog(_T("刷卡返回报文中找不到<retCode>"));
		return -1;
	}
	std::string::size_type lastIndex = strPacket.find("</retCode>");
	if(lastIndex == strPacket.npos)
	{
		writeLogErr.WriteErrLog(wFormatRecvMsg);
		writeLogErr.WriteErrLog(_T("刷卡返回报文中找不到</retCode>"));
		return -1;
	}
	std::string strErrCode = strPacket.substr(firstIndex+9,lastIndex-firstIndex-9);
	int nErrCode = 0;
	nErrCode = atoi(strErrCode.c_str());
	return nErrCode;
}
Exemplo n.º 4
0
void CSocketTcpServer::SendMsg(CString msg)
{
    char buf[MAX_BUFFER]= {0};
    m_convert.CStringToChar(msg,buf);
    for(int i=0; i<m_index; i++)
    {
        m_ol[i]->nOpType = OP_WRITE;
        memset(&m_ol[i]->ol, 0, sizeof(m_ol[i]->ol));
        strcpy_s(m_ol[i]->szBuf,MAX_BUFFER,buf);
        m_ol[i]->wsaBuf.buf=m_ol[i]->szBuf;
        m_ol[i]->wsaBuf.len = MAX_BUFFER;
        if(SOCKET_ERROR==WSASend(m_ol[i]->sock,&(m_ol[i]->wsaBuf), 1,
                                 &(m_ol[i]->dwTrans), m_ol[i]->dwFlags,
                                 &(m_ol[i]->ol), CompleteRoutine))
        {
#ifdef _DEBUG
            CString ipAddress;
            m_convert.CharToCstring(ipAddress,inet_ntoa(m_ol[i]->addr.sin_addr));
            CString errcode;
            errcode.AppendFormat(_T("client %s socket broken"),ipAddress);
            MyWriteConsole(ipAddress);
#endif
        }
    }
}
void CComplSocketClient::StopClient()
{
#ifdef _DEBUG
	MyWriteConsole(_T("WSACleanup"));
#endif
	closesocket(m_sClient);
	WSACleanup();
}
Exemplo n.º 6
0
BOOL SLZCWndScreen::SendDataToThroughScreen(const CString& str,int address,int channel,const CString& localIp)
{
	///自己公司协议
// 	int height = 0;
// 	int width = FindChannelWidth(address,channel,height);
	CString msg = str;
// #ifdef _DEBUG
//  	CString test;
// 	test.Format(_T("through wnd:address:%d,channel:%d,width:%d"),address,channel,width);
//  	MyWriteConsole(test);
// 	MyWriteConsole(str);
// #endif
//  	if(width>0 && width<=128)//注意小于128是因为同屏卡最多显示128个汉字
//  	{
//  		msg = FlushCstringToFitWndScreen(msg,width,height);
//  	}
	char buf[512]={0};
	int length = DoScreenMsg(msg,address+channel,buf);
	WriteComMsg *pMsg = new WriteComMsg;
	memset(pMsg->buf,0,DATABUFLEN);
	memcpy(pMsg->buf,buf,length);
	pMsg->length = length;
	CDoComInOut* pComInOut = CDoComInOut::GetInstance();
	pComInOut->AddWriteComMsg(pMsg);

	BOOL flag = FALSE;
	if(!localIp.IsEmpty())//UDP发送
	{
		MySocketUDP Client;
		Client.StartSocket(1024);
		flag = Client.SendTo(buf,length,localIp,1024);
		
#ifdef _DEBUG
		if(flag)
		{
			MyWriteConsole(_T("发送通屏消息成功"));
		}
		else
		{
			MyWriteConsole(_T("发送同频消息失败"));
		}
#endif
	}
	return flag;
}
BOOL CComplSocketClient::InitClient()
{
	WSADATA wsaData;
	//初始化
	if(SOCKET_ERROR==WSAStartup(MAKEWORD(2,2),&wsaData))
	{
#ifdef _DEBUG
		MyWriteConsole(_T("WSAStartup error"));
#endif
		WSACleanup();
		return FALSE;
	}
	return TRUE;
}
Exemplo n.º 8
0
DWORD WINAPI CSocketTcpServer::WorkThread(LPVOID lpParam)
{
    CSocketTcpServer* pServer = (CSocketTcpServer*) lpParam;
    CString errCode;
    while(!pServer->m_bExiteThread)
    {
        DWORD dwRet = SleepEx(INFINITE, TRUE);
        if(WAIT_IO_COMPLETION == dwRet)
        {
            continue;
        }
        else
        {
#ifdef _DEBUG
            errCode.Format(_T("SleepEx failed with error code: %d"),
                           GetLastError());
            MyWriteConsole(errCode);
#endif
        }
    }
    return 0;
}
BOOL CComplSocketClient::SendData(USHORT port,CString IP,const std::string& msg,int size,std::string& recvMsg,int& actRecvSize)
{
#ifdef _DEBUG
	CString sendMsg = _T("Send Code:");
	CString temp(msg.c_str());
	sendMsg+=temp;
	MyWriteConsole(sendMsg);
#endif
	m_sClient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(INVALID_SOCKET == m_sClient)
	{
		WSACleanup();
#ifdef _DEBUG
		MyWriteConsole(_T("socket error"));
#endif
		return FALSE;
	}
	SOCKADDR_IN ServerAddr;
	ServerAddr.sin_port = htons(port);
	ServerAddr.sin_family = AF_INET;
	///转换
	int len = CCommonConvert::CStringToChar(IP,NULL);
	char* buf = new char[len+1]; 
	ZeroMemory(buf,len+1);
	CCommonConvert::CStringToChar(IP,buf);
	////////////////////////////////////////////
	ServerAddr.sin_addr.S_un.S_addr = inet_addr(buf);
	delete []buf;
#ifdef _DEBUG
	CComputeFuncationTime connectTime;
	connectTime.SetStartTime(clock());
#endif
	if(SOCKET_ERROR==connect(m_sClient,(SOCKADDR*)&ServerAddr,
		sizeof(ServerAddr)))
	{
#ifdef _DEBUG
		MyWriteConsole(_T("connect error"));
#endif
		closesocket(m_sClient);
		return FALSE;
	}
#ifdef _DEBUG
	connectTime.SetFinshTime(clock());
	double connDur = connectTime.GetDuration();
	CString strConDur;
	strConDur.Format(_T("conntime:%f"),connDur);
	MyWriteConsole(strConDur);
#endif
	//发送
#ifdef _DEBUG
	CComputeFuncationTime sendTime;
	sendTime.SetStartTime(clock());
#endif
	setsockopt(m_sClient,SOL_SOCKET,SO_SNDTIMEO,(char *)&m_nTimeOut,sizeof(UINT));
// 	if(SOCKET_ERROR == send(m_sClient,msg.c_str(),size,0))
// 	{
// #ifdef _DEBUG
// 		MyWriteConsole(_T("send failed"));
// #endif
// 		closesocket(m_sClient);
// 		return FALSE;
// 	}
	int actSendSize = 0;
	while(true)
	{
		int tempSize = send(m_sClient,msg.c_str(),size,0);
		if(tempSize == SOCKET_ERROR)
		{
#ifdef _DEBUG
		MyWriteConsole(_T("send failed"));
#endif
			closesocket(m_sClient);
			return FALSE;
		}
		else
		{
			actSendSize += tempSize;
			if(actSendSize == size)break;
		}
	}
#ifdef _DEBUG
	sendTime.SetFinshTime(clock());
	double durSendTime = sendTime.GetDuration();
	CString strSendTime;
	strSendTime.Format(_T("sendTime:%f"),durSendTime);
	MyWriteConsole(strSendTime);
#endif
#ifdef _DEBUG
	CComputeFuncationTime recvTime;
	recvTime.SetStartTime(clock());
#endif
	//接收
	char recvBuf[MAXRECVBUF+1]={0};
	setsockopt(m_sClient,SOL_SOCKET,SO_RCVTIMEO,(char *)&m_nTimeOut,sizeof(UINT));
	while(true)
	{
 		memset(recvBuf,0,MAXRECVBUF+1);
		actRecvSize = recv(m_sClient,recvBuf,MAXRECVBUF,0);
		std::string recvTemp(recvBuf);
#ifdef _DEBUG
		CString tremp(recvBuf);
		MyWriteConsole(tremp);
#endif
		if(recvTemp.find("</dataPacket>") != recvTemp.npos)//找结尾
		{
			recvMsg += recvTemp;
			break;
		}
		if(actRecvSize==SOCKET_ERROR || actRecvSize==0)
		{
			break; 	
		}
		else
		{
			recvMsg += recvTemp;
		}
	}
#ifdef _DEBUG
	recvTime.SetFinshTime(clock());
	double durRecvTime = recvTime.GetDuration();
	CString strRecvTime;
	strRecvTime.Format(_T("recvTime:%f"),durRecvTime);
	MyWriteConsole(strRecvTime);
	MyWriteConsole(_T("send ok"));
#endif
	closesocket(m_sClient);
	return TRUE;
}
Exemplo n.º 10
0
BOOL CComplSocketClient::SendData(USHORT port,CString IP,char buf[],int size)
{

	m_sClient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(INVALID_SOCKET == m_sClient)
	{
		WSACleanup();



#ifdef _DEBUG
		MyWriteConsole(_T("socket error"));
#endif



		return FALSE;
	}
	SOCKADDR_IN ServerAddr;
	ServerAddr.sin_port = htons(port);
	ServerAddr.sin_family = AF_INET;
	///转换
	int len = CCommonConvert::CStringToChar(IP,NULL);
	char* aIP = new char[len+1]; 
	ZeroMemory(aIP,len+1);
	CCommonConvert::CStringToChar(IP,aIP);
	////////////////////////////////////////////
	ServerAddr.sin_addr.S_un.S_addr = inet_addr(aIP);
	delete [] aIP;


#ifdef _DEBUG
	CComputeFuncationTime connectTime;
	connectTime.SetStartTime(clock());
#endif


	if(SOCKET_ERROR==connect(m_sClient,(SOCKADDR*)&ServerAddr,
		sizeof(ServerAddr)))
	{

#ifdef _DEBUG
		MyWriteConsole(_T("connect error"));
#endif

		closesocket(m_sClient);
		return FALSE;
	}


#ifdef _DEBUG
	connectTime.SetFinshTime(clock());
	double connDur = connectTime.GetDuration();
	CString strConDur;
	strConDur.Format(_T("conntime:%f"),connDur);
	MyWriteConsole(strConDur);
#endif


	//发送
#ifdef _DEBUG
	CComputeFuncationTime sendTime;
	sendTime.SetStartTime(clock());
#endif

	
	



	setsockopt(m_sClient,SOL_SOCKET,SO_SNDTIMEO,(char *)&m_nTimeOut,sizeof(UINT));
	
	int actSendSize = 0;
	while(true)
	{
		int tempSize = send(m_sClient,buf,size,0);
		if(tempSize == SOCKET_ERROR)
		{
#ifdef _DEBUG
			MyWriteConsole(_T("send failed"));
#endif
			closesocket(m_sClient);
			return FALSE;
		}
		else
		{
			actSendSize += tempSize;
			if(actSendSize >= size)break;
		}
	}


#ifdef _DEBUG
	sendTime.SetFinshTime(clock());
	double durSendTime = sendTime.GetDuration();
	CString strSendTime;
	strSendTime.Format(_T("sendTime:%f"),durSendTime);
	MyWriteConsole(strSendTime);
#endif

// 	char recvBuf[MAXRECVBUF+1]={0};
// 	setsockopt(m_sClient,SOL_SOCKET,SO_RCVTIMEO,(char *)&m_nTimeOut,sizeof(UINT));
// 	
// 	memset(recvBuf,0,MAXRECVBUF+1);
// 	int actRecvSize = recv(m_sClient,recvBuf,MAXRECVBUF,0);
// 	std::string recvTemp(recvBuf);

	
	closesocket(m_sClient);
	return TRUE;
}
Exemplo n.º 11
0
DWORD WINAPI CDoComInOut::ReadCallerThread(LPVOID pParam)
{
	while(TRUE)
	{
		CDoComInOut* pThis=(CDoComInOut*)pParam;
		char buf[1024]={0};
		DWORD dwReaded=0;//读到的大小
		BOOL bres=FALSE;
		DWORD dwErrorFlags;
		COMSTAT ComStat;
//		OVERLAPPED m_osRead;
//		memset(&m_osRead,0,sizeof(OVERLAPPED));
		CComInit* pComInit = CComInit::GetInstance();
		if(pComInit->m_hComWndScreen
			!=INVALID_HANDLE_VALUE)
		{	
			//////考虑枷锁
			ClearCommError(pComInit->m_hComWndScreen,&dwErrorFlags,&ComStat);
			Sleep(100);
			bres=ReadFile(pComInit->m_hComWndScreen,buf,1024,&dwReaded,&pComInit->m_read_os);
			if(!bres)
			{
				if(GetLastError()==ERROR_IO_PENDING)
				{
					while(!GetOverlappedResult(pComInit->m_hComWndScreen, &pComInit->m_read_os,&dwReaded,TRUE))
					{
						dwErrorFlags = GetLastError();
						if(dwErrorFlags == ERROR_IO_INCOMPLETE) continue;
						else{
							ClearCommError(pComInit->m_hComWndScreen,&dwErrorFlags, &ComStat ) ;
							break;
						}
					}
				}
			}
			if(dwReaded>0)//读到了
			{
#ifdef _DEBUG
				unsigned char uBuf[1024]={0};
				memcpy(uBuf,buf,dwReaded);
				CString temp;
				for(UINT i=0;i<dwReaded;i++)
				{
					temp+=_T("0x");
					temp.AppendFormat(_T("%08x"),uBuf[i]);
					temp+=_T(" ");
				}
				MyWriteConsole(temp);
				MyWriteConsole(_T("------------------------------------------"));
				CString strBuf;
				CCommonConvert convert;
				convert.CharToCstring(strBuf,buf);
				MyWriteConsole(strBuf);
				MyWriteConsole(_T("------------------------------------------"));
				CString strDwread;
				MyWriteConsole(strDwread);
#endif
				//////不是呼叫器和评价的数据,注:呼叫器评价器数据以0xff,0x68开始,0x16结束
				if(buf[0]==(char)0xA0 && buf[1]==(char)0x90 && buf[dwReaded-1]==(char)0xAA && 
					buf[dwReaded-2]==(char)0xA5)
				{
					int wndID = buf[2];//屏地址
#ifdef _DEBUG
					CString str;
					str.Format(_T("屏地址:%d发送成功"),wndID);
					MyWriteConsole(str);
#endif
					//条屏,综合屏数据,发送成功
				}
				else if((buf[0]!=(char)0xff&&buf[2]!=(char)0x68) && buf[dwReaded-1]!=(char)0x16)
				{
					//通屏数据
					if(!pThis->m_isDoneThroughInit)
					{
// #ifdef _DEBUG
// 						MyWriteConsole(_T("同频数据"));
// #endif
// 						SLZCWndScreen* pWindowScreen = SLZCWndScreen::GetInstance();
// 						pWindowScreen->AddThroughInitStr(buf,dwReaded);

					}
				}
				else
				{
					if(buf[5]>0xffffff80)
					{/////////平价器消息
						//返回给评价器信息
						char evabuf[8]={0};
						pThis->m_pSlzEvaluator->SystemSendToEva(evabuf,buf);
						WriteComMsg* pMsg = new WriteComMsg;;
 						memset(pMsg->buf,0,DATABUFLEN);
						memcpy(pMsg->buf,evabuf,8);
						pMsg->length = 8;
						pThis->AddWriteComMsg(pMsg);
						WaitForSingleObject(pThis->m_hWriteComThread,80);
						//判断评价超时并改值(当前一次评价没结束时,(同一个评价器)
						//又来一个评价,需要判断改值
						pThis->m_pSlzEvaluator->IsOutTimeAndReser(buf);
						//处理评价数据
						pThis->m_pSlzEvaluator->DoEvaltorMsg(buf);
					}
					else
					{//////////呼叫器消息
						//呼叫器消息
						WriteComMsg* pMsg = new WriteComMsg;
						memset(pMsg->buf,0,DATABUFLEN);
						memcpy(pMsg->buf,buf,dwReaded);
						pMsg->length = dwReaded;
						pThis->AddWriteComMsg(pMsg);
						WaitForSingleObject(pThis->m_hWriteComThread,80);
						pThis->m_pSlzCaller->DoReadMsg(dwReaded,buf);
					}	
				}
			}
			////////////////解锁
		}
		else
		{
			Sleep(20);
		}
	}
	return 0;
}
Exemplo n.º 12
0
DWORD WINAPI CDoComInOut::WriteComThread(LPVOID pParam)
{
	while(TRUE)
	{
		CDoComInOut* pThis = (CDoComInOut*)pParam;
		if(pThis->m_list_writeComMsg.size()==0)
		{
			Sleep(10);
		}
		else
		{
			pThis->m_readComLock.Lock();
			list<WriteComMsg*>::const_iterator itera = pThis->m_list_writeComMsg.begin();
			WriteComMsg* pMsg = *itera;
//			pThis->m_list_writeComMsg.erase(itera);
			pThis->m_list_writeComMsg.pop_front();
			pThis->m_readComLock.Unlock();
			CComInit* pComInit = CComInit::GetInstance();
			
			DWORD       dwErrorFlags;
			DWORD   	dwError;
			COMSTAT     ComStat;
#ifdef _DEBUG
			CString strLength;
			strLength.Format(_T("msg length:%d"),pMsg->length);
			MyWriteConsole(strLength);
#endif
//			OVERLAPPED osWrite;
//			memset(&osWrite,0,sizeof(osWrite));
//			do
//			{
				DWORD dwTrans;
				BOOL bWriteStat = WriteFile(pComInit->m_hComWndScreen,pMsg->buf,
					pMsg->length,NULL,&pComInit->m_write_os);
				if(!bWriteStat)
				{
					if(GetLastError()==ERROR_IO_PENDING)
					{	 
						while(!GetOverlappedResult(pComInit->m_hComWndScreen,&pComInit->m_write_os,&dwTrans,TRUE)){
							dwError = GetLastError();
							if(dwError == ERROR_IO_INCOMPLETE){
								continue;
							}
							else{
								 ClearCommError(pComInit->m_hComWndScreen, &dwErrorFlags, &ComStat ) ;
							}
						}
					}
				}
				
// #ifdef _DEBUG
// 				CString strCount;
// 				strCount.Format(_T("dwAcWrite:%d"),dwAcWrite);
// 				MyWriteConsole(strCount);
// #endif
//			}while(dwAcWrite < (UINT)pMsg->length);
			
// 			PurgeComm( pComInit->m_hComWndScreen, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR
// 				| PURGE_RXCLEAR );
			delete pMsg;
		}
	}
	return 0;
}
Exemplo n.º 13
0
void CALLBACK CSocketTcpServer::CompleteRoutine(DWORD dwError,
        DWORD dwTrans,
        LPWSAOVERLAPPED Overlppad,
        DWORD dwFlags)
{
    int nIndex = 0;
    for(; nIndex<g_scoketTcpServer->m_index; nIndex++)
    {
        if(&g_scoketTcpServer->m_ol[nIndex]->ol == Overlppad)
        {
            break;
        }
    }
    CString ipAddress;
    g_scoketTcpServer->m_convert.CharToCstring(ipAddress,
            inet_ntoa(g_scoketTcpServer->m_ol[nIndex]->addr.sin_addr));
    CString errCode;
    if(0 != dwError || 0 == dwTrans)
    {
#ifdef _DEBUG
        errCode.Format(_T("Client: <%s : %d> leave...."),
                       ipAddress,
                       ntohs(g_scoketTcpServer->m_ol[nIndex]->addr.sin_port));
        MyWriteConsole(errCode);
#endif
        closesocket(g_scoketTcpServer->m_ol[nIndex]->sock);
#ifdef _DEBUG
        errCode.Format(_T("%d nIndex from array"),nIndex);
        MyWriteConsole(errCode);
#endif
        delete g_scoketTcpServer->m_ol[nIndex];
        // Error or closesocket by peer
        for(int i=nIndex; i<g_scoketTcpServer->m_index-1; i++)
        {
            g_scoketTcpServer->m_ol[i] = g_scoketTcpServer->m_ol[i+1];
        }
        g_scoketTcpServer->m_index--;
    }
    else
    {
        switch(g_scoketTcpServer->m_ol[nIndex]->nOpType)
        {
        case OP_READ:
        {
#ifdef _DEBUG
            CString msg;
            g_scoketTcpServer->m_convert.CharToCstring(msg,
                    g_scoketTcpServer->m_ol[nIndex]->szBuf);
            errCode.Format(_T("recv <%s : %d> data: %s"),
                           ipAddress,
                           ntohs(g_scoketTcpServer->m_ol[nIndex]->addr.sin_port),
                           msg);
            MyWriteConsole(errCode);
#endif
            g_scoketTcpServer->m_ol[nIndex]->nOpType = OP_WRITE;
            memset(&(g_scoketTcpServer->m_ol[nIndex]->ol), 0,
                   sizeof(g_scoketTcpServer->m_ol[nIndex]->ol));
            //////////把接收到的报文拷贝到string
            std::string recvPacket(g_scoketTcpServer->m_ol[nIndex]->szBuf);
            ///判断报文
            CProducePacket producePacket;
            int iErrCode = producePacket.JudgeSendPacket(recvPacket);
            switch(iErrCode)
            {
            case 1:
            case 26:
            case 27:
            case 28:
            case 32:
            case 33:
            case 34:
            case 35:
                g_scoketTcpServer->m_pDealData->AddPacket(recvPacket);
                break;
            }
            //返回报文
            std::string retPacket;
            retPacket = producePacket.ProduceSendRet(iErrCode,recvPacket);
            int size = retPacket.size();
            strncpy_s(g_scoketTcpServer->m_ol[nIndex]->szBuf,MAX_BUFFER,retPacket.c_str(),MAX_BUFFER-1);
            g_scoketTcpServer->m_ol[nIndex]->wsaBuf.buf = g_scoketTcpServer->m_ol[nIndex]->szBuf;
            g_scoketTcpServer->m_ol[nIndex]->wsaBuf.len=MAX_BUFFER;

            if(SOCKET_ERROR  == WSASend(g_scoketTcpServer->m_ol[nIndex]->sock,
                                        &(g_scoketTcpServer->m_ol[nIndex]->wsaBuf), 1,
                                        &(g_scoketTcpServer->m_ol[nIndex]->dwTrans),
                                        g_scoketTcpServer->m_ol[nIndex]->dwFlags,
                                        &(g_scoketTcpServer->m_ol[nIndex]->ol),
                                        CompleteRoutine))
            {
                if(WSA_IO_PENDING != WSAGetLastError())
                {
#ifdef _DEBUG
                    errCode.Format(_T("WSASend failed with error code: %d"),
                                   WSAGetLastError());
                    MyWriteConsole(errCode);
#endif
                    closesocket(g_scoketTcpServer->m_ol[nIndex]->sock);
                    // Error or closesocket by peer
                    for(int i=nIndex; i<g_scoketTcpServer->m_index-1; i++)
                    {
                        g_scoketTcpServer->m_ol[i] = g_scoketTcpServer->m_ol[i+1];
                    }
                    g_scoketTcpServer->m_index--;
                }
            }
        }
        break;
        case OP_WRITE:
        {
            g_scoketTcpServer->m_ol[nIndex]->nOpType = OP_READ;
            dwFlags = 0;
            memset(&(g_scoketTcpServer->m_ol[nIndex]->ol), 0,
                   sizeof(g_scoketTcpServer->m_ol[nIndex]->ol));
            memset(g_scoketTcpServer->m_ol[nIndex]->szBuf, 0,
                   sizeof(g_scoketTcpServer->m_ol[nIndex]->szBuf));
            g_scoketTcpServer->m_ol[nIndex]->wsaBuf.buf =
                g_scoketTcpServer->m_ol[nIndex]->szBuf;
            dwTrans = g_scoketTcpServer->m_ol[nIndex]->wsaBuf.len = MAX_BUFFER;
            if(SOCKET_ERROR == WSARecv(g_scoketTcpServer->m_ol[nIndex]->sock,
                                       &(g_scoketTcpServer->m_ol[nIndex]->wsaBuf), 1,
                                       &dwTrans, &dwFlags,
                                       &(g_scoketTcpServer->m_ol[nIndex]->ol),
                                       CompleteRoutine))
            {
                if(WSA_IO_PENDING != WSAGetLastError())
                {
#ifdef _DEBUG
                    errCode.Format(_T("WSARecv failed with error code: %d"),
                                   WSAGetLastError());
                    MyWriteConsole(errCode);
#endif
                    closesocket(g_scoketTcpServer->m_ol[nIndex]->sock);
                    // Error or closesocket by peer
                    for(int i=nIndex; i<g_scoketTcpServer->m_index-1; i++)
                    {
                        g_scoketTcpServer->m_ol[i] = g_scoketTcpServer->m_ol[i+1];
                    }
                    g_scoketTcpServer->m_index--;
                }
            }
        }
        break;
        }
    }
}
Exemplo n.º 14
0
DWORD WINAPI CSocketTcpServer::AcceptThread(LPVOID lpParam)
{
    CSocketTcpServer* pServer = (CSocketTcpServer*)lpParam;
#ifdef _DEBUG
    CString errCode;
    errCode=_T("server start wait for client......");
    MyWriteConsole(errCode);
#endif
    while(1)
    {
        SOCKADDR_IN remote = {0};
        int len = sizeof(remote);
        SOCKET sNew;
        try {
            ASSERT(&pServer->m_SockBound);
            sNew = accept(pServer->m_SockBound,(LPSOCKADDR)&remote,&len);
        }
        catch(...)
        {

        }
        if(INVALID_SOCKET == sNew)
        {
#ifdef _DEBUG
            errCode.Format(_T("accept err code:%d"),WSAGetLastError());
            MyWriteConsole(errCode);
#endif
            continue;
        }
        else
        {
            CString ipAddress;
            pServer->m_convert.CharToCstring(ipAddress,inet_ntoa(remote.sin_addr));
#ifdef _DEBUG
            CString clientInfo;
            clientInfo.Format(_T("Client <%s : %d> come in..."),ipAddress,
                              ntohs(remote.sin_port));
            MyWriteConsole(clientInfo);
#endif
            pServer->m_ol[pServer->m_index] = new OVERLAPPEDINFO;
            pServer->m_ol[pServer->m_index]->sock = sNew;
            pServer->m_ol[pServer->m_index]->nOpType = OP_READ;
            memcpy(&(pServer->m_ol[pServer->m_index]->addr), &remote,
                   sizeof(remote));
            if(SOCKET_ERROR == WSARecv(pServer->m_ol[pServer->m_index]->sock,
                                       &pServer->m_ol[pServer->m_index]->wsaBuf,
                                       1,&pServer->m_ol[pServer->m_index]->dwTrans,
                                       &pServer->m_ol[pServer->m_index]->dwFlags,
                                       &pServer->m_ol[pServer->m_index]->ol,
                                       CompleteRoutine))
            {
                if(WSA_IO_PENDING != WSAGetLastError())
                {
#ifdef _DEBUG
                    errCode.Format(_T("WSARecv failed with error code: %d"),
                                   WSAGetLastError());
                    MyWriteConsole(errCode);
#endif
                    closesocket(pServer->m_ol[pServer->m_index]->sock);
                    delete pServer->m_ol[pServer->m_index];
                    pServer->m_ol[pServer->m_index] = NULL;
                    continue;
                }
            }
            pServer->m_index++;
        }
    }
    return 0;
}