⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 clientsocket.cpp

📁 vc++6.0开发网络典型应用实例导航 1. 本光盘提供了本书中所有的实例源程序文件。 2. 附录文件夹下是Winsock 函数参考以及错误码列表
💻 CPP
📖 第 1 页 / 共 2 页
字号:
									   "<TD><B>Date</B></TD></TR>\r\n";

	CFileFind find;
	
	// first list directories
	BOOL bFound = find.FindFile(strLocalPath + "\\*.*");
	while (bFound)
	{
		bFound = find.FindNextFile();
		
		// skip "." and ".." 
		if (find.IsDots())
			continue;

		if (find.IsDirectory())
		{
			strResult += "<TR><TD><A HREF=\"";
			strResult += lpszURL;
			strResult.TrimRight('/');
			strResult += "/";
			strResult += find.GetFileName();
			strResult += "/";
			strResult += "\">";
			strResult += find.GetFileName();
			strResult += "</A></TD><TD>-</TD><TD>-</TD></TR>\r\n";
		}
	}
	find.Close();

	// and finally list files
	bFound = find.FindFile(strLocalPath + "\\*.*");
	while (bFound)
	{
		bFound = find.FindNextFile();
		
		// skip "." and ".." 
		if (find.IsDots())
			continue;

		if (!find.IsDirectory())
		{
			strResult += "<TR><TD><A HREF=\"";
			strResult += lpszURL;
			strResult.TrimRight('/');
			strResult += "/";
			strResult += find.GetFileName();
			strResult += "\">";
			strResult += find.GetFileName();
			strResult += "</A></TD><TD>";
			strResult += ToString(find.GetLength());
			strResult += "</TD><TD>";
			CTime creationTime;
			find.GetCreationTime(creationTime);
			strResult += creationTime.Format("%m/%d/%Y %H:%M:%S");
			strResult += "</TD></TR>\r\n";
		}
	}
	strResult += "</TABLE></BODY></HTML>\r\n";

	// put the data into the socket...
	SendData(strResult);

	((CClientThread *)m_pThread)->PostStatusMessage("Transfer (listing) complete");

	// close the connection.
	Close();
	m_pThread->PostThreadMessage(WM_QUIT,0,0);
	return TRUE;
}


/********************************************************************/
/*																	*/
/* Function name : SendHeader										*/		
/* Description   : Send header information							*/
/*																	*/
/********************************************************************/
BOOL CClientSocket::SendHeader(LPCTSTR lpszFilename)
{
	CFileStatus status;
	
	CFile::GetStatus(lpszFilename, status);

	DWORD dwBytes = status.m_size;

	CString strHeader;
	// HTTP version
	strHeader =	"HTTP/1.0 ";
	// status
	strHeader += "200 OK\r\n";
	// servername
	strHeader += "Server: Mini ASP Web Server\r\n";

	CString strExtension;
	_splitpath(lpszFilename, NULL, NULL, NULL, strExtension.GetBuffer(5));
	strExtension.ReleaseBuffer();

	// content type
	for (int i = 0; i < m_nMIMELength; i++)
	{
		if (strExtension.CompareNoCase(m_MIMETypes[i].lpszExtension) == 0)
		{
			strHeader += "Content-Type: ";
			strHeader += m_MIMETypes[i].lpszType;
			strHeader += "\r\n";
			break ;
		}
	}
	
	// file length
	CString strLength;
	strLength.Format("Content-Length: %d\r\n", dwBytes);
	strHeader += strLength;
	
	SYSTEMTIME systemTime;
	status.m_mtime.GetAsSystemTime(systemTime);

	// get internet time
	char buff[INTERNET_RFC1123_BUFSIZE];
	InternetTimeFromSystemTime(&systemTime, INTERNET_RFC1123_FORMAT,
									buff, INTERNET_RFC1123_BUFSIZE);

	// modified	
	strHeader += "Last-Modified: ";
	strHeader += CString(buff);
	strHeader += "\r\n\r\n";

	// send header to client
	SendData(strHeader);
	return TRUE;
}


/********************************************************************/
/*																	*/
/* Function name : SendError										*/		
/* Description   : Send error information							*/
/*																	*/
/********************************************************************/
BOOL CClientSocket::SendError(LPCTSTR lpszMessage)
{
	CString strHeader;
	// HTTP version
	strHeader =	"HTTP/1.0 ";
	// status
	strHeader += lpszMessage;
	
	strHeader += "\r\n";
	
	// servername
	strHeader += "Server: Mini ASP Web Server\r\n";

	SYSTEMTIME systemTime;
	GetLocalTime(&systemTime);

	// get internet time
	char buff[INTERNET_RFC1123_BUFSIZE];
	InternetTimeFromSystemTime(&systemTime, INTERNET_RFC1123_FORMAT,
									buff, INTERNET_RFC1123_BUFSIZE);

	// modified	
	strHeader += "Date: ";
	strHeader += CString(buff);
	strHeader += "\r\n\r\n";
	
	// put the data into the socket...
	SendData(strHeader);

	((CClientThread *)m_pThread)->PostStatusMessage("ERROR: " + CString(lpszMessage));

	Close();
	// tell thread to shutdown
	m_pThread->PostThreadMessage(WM_QUIT,0,0);
	return TRUE;
}


/************************************************************************/
/*																		*/
/* Function name : SendFile												*/
/* Description   : Get a string containing all the HTTP headers			*/
/*				   associated with this object in a format suitable for */
/*				   sending to a client.									*/
/*																		*/
/************************************************************************/
BOOL CClientSocket::SendFile(LPCTSTR lpszFileName)
{
	CString strFileName = lpszFileName;
	BOOL bResult = FALSE;
	CFile file;

	// specified a filename ?
	if ((GetFileAttributes(strFileName) & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)
	{
		// display default file
		strFileName.TrimRight('\\');
		strFileName += '\\';
		strFileName += "index.html";
	}
	
	// is path subdirectory of home ?
	if (!IsSubDirectory(m_strHomeDir, strFileName))
	{
		SendError("403 Forbidden");
		return FALSE;
	}

	// valid filename ?
	if (FileExists(strFileName, FALSE))
	{
		// log command
		((CClientThread *)m_pThread)->PostStatusMessage("Sending file: " + strFileName);

		bResult = file.Open(lpszFileName, CFile::modeRead | CFile::typeBinary);
		if (!bResult)
		{
			SendError("404 Not Found");
			return TRUE;
		}
		bResult = SendHeader(file.GetFileName());
		if (bResult)
		{
			char buff[PACKET_SIZE];
			int nRead;

			try
			{
				CSocketFile sockFile(this, FALSE);
				while ((nRead = file.Read (buff, PACKET_SIZE)) > 0) 
				{
					sockFile.Write((LPVOID)buff, nRead);
				}
				sockFile.Flush();
			}
			catch(CFileException *e)
			{
				char szError[128];
				e->GetErrorMessage(szError, sizeof(szError));
				e->Delete();
				TRACE1("SendFile error: %s\n", szError);
			}
		}
		file.Close();

		((CClientThread *)m_pThread)->PostStatusMessage("Transfer complete");

		// close the connection.
		Close();
		m_pThread->PostThreadMessage(WM_QUIT,0,0);
	}
	return bResult;
}


/************************************************************************/
/*																		*/
/* Function name : SendData												*/
/* Description   : Send specified data to client						*/
/*																		*/
/************************************************************************/
BOOL CClientSocket::SendData(LPCTSTR lpszData)
{
	int nCount = lstrlen(lpszData);

	// send data and keep message pump running...
	CSocketFile sockFile(this, FALSE);
	try
	{
		sockFile.Write(lpszData, nCount);
	}
	catch(...)
	{
		return FALSE;
	}
	sockFile.Flush();
	return TRUE;
}


/********************************************************************/
/*																	*/
/* Function name : ExecuteAspPage									*/		
/* Description   : Execute ASP page and send result to client.		*/
/*																	*/
/********************************************************************/
BOOL CClientSocket::ExecuteAspPage(LPCTSTR lpszFileName)
{
	// log command
	((CClientThread *)m_pThread)->PostStatusMessage("Executing ASP file: " + CString(lpszFileName));

	// is path subdirectory of home ?
	if (!IsSubDirectory(m_strHomeDir, lpszFileName))
	{
		SendError("403 Forbidden");
		return FALSE;
	}

	// load the code in memory
	CString strAspCode;
	if (!m_AspParser.LoadFile(lpszFileName, strAspCode))
	{
		SendError("404 Not Found");
		return FALSE;
	}

	// initialize parser
	if (m_AspParser.Initialize())
	{
		// set current directory
		CString strDirectory = lpszFileName;
		int nPos = strDirectory.ReverseFind('\\');
		if (nPos != -1)
		{
			m_AspParser.SetCurrentDirectory(strDirectory.Left(nPos));
		}
		
		// set root directory
		m_AspParser.SetRootDirectory(m_strHomeDir);

		// set some server variables
		InitializeServerVariables();

		// extract query params
		m_AspParser.ParseQueryString(m_QueryParams);

		// extract form variables
		m_AspParser.ParseFormVars(m_FormVars);

		// extract request cookies
		CString strCookies;
		if (GetServerVariable("Cookie", strCookies))
			m_AspParser.ParseRequestCookies(strCookies);

		// execute the code
		BOOL bResult = m_AspParser.Execute(strAspCode);

		// get response buffer
		CString strResult;

		if (bResult)
			m_AspParser.GetResponseBuffer(strResult);
		else
			strResult = m_AspParser.GetLastError();

		CString strRedirectURL;
		CString strHeader;

		// HTTP version
		strHeader =	"HTTP/1.0 ";

		// do we have a redirect request ?
		if (!m_AspParser.GetRedirectURL(strRedirectURL))
		{
			// status
			strHeader += "200 OK\r\n";
			// servername
			strHeader += "Server: Mini ASP Web Server\r\n";
			// content type
			strHeader += "Content-Type: text/html\r\n";
			// file length
			CString strLength;
			strLength.Format("Content-Length: %d\r\n", strResult.GetLength());
			strHeader += strLength;
			
			SYSTEMTIME systemTime;
			GetSystemTime(&systemTime);

			// get internet time
			char buff[INTERNET_RFC1123_BUFSIZE];
			InternetTimeFromSystemTime(&systemTime, INTERNET_RFC1123_FORMAT,
											buff, INTERNET_RFC1123_BUFSIZE);

			// modified	
			strHeader += "Last-Modified: ";
			strHeader += CString(buff);
			strHeader += "\r\n";

			CString strCookies;
			if (m_AspParser.m_pResponseObject->RenderCookies(strCookies))
			{
				strHeader += strCookies;
			}
			
			strHeader += "\r\n\r\n";
			strHeader += strResult;
		}
		else
		{
			// create redirect header
			strHeader += "302 Object Moved\r\n";
			strHeader += "Location: ";
			strHeader += strRedirectURL;
			strHeader += "\r\n\r\n";
		}

		m_AspParser.CleanUp();

		// put the data into the socket...
		SendData(strHeader);

		// close the connection.
		Close();
		m_pThread->PostThreadMessage(WM_QUIT,0,0);
		return TRUE;
	}
	return FALSE;
}


/************************************************************************/
/*																		*/
/* Function name : RenderHeaders										*/
/* Description   : Get a string containing all the HTTP headers			*/
/*				   associated with this object in a format suitable for */
/*				   sending to a client.									*/
/*																		*/
/************************************************************************/
void CClientSocket::RenderHeaders(CString& strHeaders)
{
	CString strKey, strValue;

	// Iterate through the entire map
	for(int i=0; i<m_Headers.GetSize(); i++)
	{
		strKey = m_Headers.GetKeyAt(i);
		strValue = m_Headers.GetValueAt(i);

		strHeaders += strKey;
		strHeaders += ": ";
		strHeaders += strValue;
		strHeaders += "\r\n";
	} 
	strHeaders += "\r\n";
}


/************************************************************************/
/*																		*/
/* Function name : GetServerVariable									*/
/* Description   : Retrieve the value of the requested server variable.	*/
/*																		*/
/************************************************************************/
BOOL CClientSocket::GetServerVariable(LPTSTR lpszVariable, CString &strValue)
{
	CString strKey;

	// Iterate through the entire map
	for(int i=0; i<m_Headers.GetSize(); i++)
	{
		strKey = m_Headers.GetKeyAt(i);
		if (strKey.CompareNoCase(lpszVariable) == 0)
		{
			strValue = m_Headers.GetValueAt(i);
			return TRUE;
		}
	} 
	// not found
	return FALSE;
}


/********************************************************************/
/*																	*/
/* Function name : InitializeServerVariables						*/
/* Description   : Populate the ServerVariables collection.			*/
/*																	*/
/********************************************************************/
void CClientSocket::InitializeServerVariables()
{
    char szBuff[MAX_COMPUTERNAME_LENGTH + 1];
	DWORD dwSize = MAX_COMPUTERNAME_LENGTH + 1;

    GetUserName(szBuff, &dwSize);
    m_AspParser.m_pRequestObject->AddServerVariablesKey("LOGON_USER", szBuff);
    
	// failes on Windows 2000/XP !
    GetComputerName(szBuff, &dwSize);
	m_AspParser.m_pRequestObject->AddServerVariablesKey("SERVER_NAME", szBuff);

	m_AspParser.m_pRequestObject->AddServerVariablesKey("SERVER_SOFTWARE", "Pablo Software Solutions ASP demo/1.0");
	m_AspParser.m_pRequestObject->AddServerVariablesKey("SERVER_PROTOCOL", "HTTP/1.0");

	m_AspParser.m_pRequestObject->AddServerVariablesKey("REQUEST_METHOD", m_nRequestMethod ? "GET" : "POST");

	CString strVariable;

	// get local ip
	UINT nPort;
	CString strIPAddress;
	GetSockName(strIPAddress, nPort);
	m_AspParser.m_pRequestObject->AddServerVariablesKey("LOCAL_ADDR", strIPAddress);

	strVariable.Format("%u", nPort);
	m_AspParser.m_pRequestObject->AddServerVariablesKey("SERVER_PORT", strVariable);
	
	// get remote ip
	GetPeerName(strIPAddress, nPort);
	m_AspParser.m_pRequestObject->AddServerVariablesKey("REMOTE_ADDR", strIPAddress);
	
	if (GetServerVariable("Host", strVariable))
		m_AspParser.m_pRequestObject->AddServerVariablesKey("REMOTE_HOST", strVariable);
		
	if (GetServerVariable("User-Agent", strVariable))
		m_AspParser.m_pRequestObject->AddServerVariablesKey("HTTP_USER_AGENT", strVariable);

	if (GetServerVariable("Accept", strVariable))
		m_AspParser.m_pRequestObject->AddServerVariablesKey("HTTP_ACCEPT", strVariable);

	m_AspParser.m_pRequestObject->AddServerVariablesKey("QUERY_STRING", m_QueryParams);

	if (GetServerVariable("script_name", strVariable))
		m_AspParser.m_pRequestObject->AddServerVariablesKey("SCRIPT_NAME", strVariable);

	if (GetServerVariable("path_info", strVariable))
		m_AspParser.m_pRequestObject->AddServerVariablesKey("PATH_INFO", strVariable);

	if (GetServerVariable("path_translated", strVariable))
		m_AspParser.m_pRequestObject->AddServerVariablesKey("PATH_TRANSLATED", strVariable);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -