Esempio n. 1
0
int	CSrvSock::UdpWaiting(int sd)
{
	int	ret;

	if ((data_sess == NULL) || (RecvFunc == NULL))
	{
		return	TLV_NO;
	}

	ret = RecvFunc(sd, data_sess);
	if (data_sess == NULL)
	{
		ret = TLV_NO;	//	session disconnected
	}
	else
	{
		ret = TLV_YES;	//	disconnected by network peoblem
	}

	return	ret;
}
Esempio n. 2
0
void CIocpClient::RecvThreadLoop()
{
	for (;;)
	{
		if(m_bThreadStopFlag)
			break;
		sleep(30);
		/////////////////////////////连接服务器//////////////////////////////////
		if (m_bConnected == false)		
		{	// 初始化socket套接字,并设为非阻塞模式
			if (m_sock != INVALID_SOCKET)
			{
				closesocket(m_sock);
				m_sock = INVALID_SOCKET;	
				sleep(500);
			}
			m_sock = socket(AF_INET, SOCK_STREAM, 0);   
			unsigned long ul = 1;
			ioctlsocket(m_sock, FIONBIO, (unsigned long *)&ul);		
			// 向服务器建立Socket连接
			const char *cip = m_server_IP.c_str();
			SOCKADDR_IN addrSrv;   
			addrSrv.sin_addr.S_un.S_addr = inet_addr(cip);   
			addrSrv.sin_family = AF_INET;   
			addrSrv.sin_port = htons(m_server_PORT);
			int nRet = ::connect(m_sock,(SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
			cout<<"[...] IocpClient: Connecting......to "<<m_server_IP<<":"<<m_server_PORT<<endl;
			sleep(500);
			// 用recv测试连接状态结果
			if(nRet == SOCKET_ERROR)
			{	
				::recv(m_sock, m_pRecvBuff, IOCPCLIENT_IN_BUF_LEN, 0);
				int err = WSAGetLastError();
				if (err != WSAEWOULDBLOCK)
				{
					cout<<"[!!!] IocpClient: Connect Failed! ErrCode:"<<err<<endl;
					continue;	// 自动重新尝试建立连接
				}
			}
			// 连接服务器成功!
			cout<<"[...] IocpClient: Connected OK!"<<endl;
			m_bConnected = true;
			Write(CLSERVER, "hello", sizeof("hello"));
		}
		/////////////////////////////接收数据///////////////////////////////////
		int recvlen = ::recv(m_sock, m_pRecvBuff, IOCPCLIENT_IN_BUF_LEN, 0);	
		int err = 0;
		if(recvlen == SOCKET_ERROR)				
		{
			err = WSAGetLastError();
			if (WSAEWOULDBLOCK != err)	// 连接断开
			{
				m_bConnected = false;	// 自动重连
			}
		}
		else if(recvlen > 0)			// 收到数据
		{
			if(RecvFunc != NULL)
			{
				err = RecvFunc(recvlen);			// 解析处理接收报文
				if(err != 0)
					cout<<"[!!!] IocpClient: 报文接收到,但解析时报错,可能格式内容有误: "<<err<<endl;
			}
		}
		else{}
	}// end of for(;;)
	//////////////////////////////////////////////////////////////////////////
	// 退出线程时关闭释放
	if (m_bConnected)
	{
		// 关闭套接字sock
		if (m_sock != INVALID_SOCKET)
		{
			closesocket(m_sock);
			m_sock = INVALID_SOCKET;
			sleep(500);
		}
		m_bConnected = false;
	}
}