示例#1
0
//////////////////////////
//	Read header & populate string with body
//////////////////////////
bool CMimeProtocol::readMimeResponse(int link,CHARPTR headers,int size,StringObject& content)
{
	CHAR buffer[CBUFF_HUGE+2];

	CHARPTR ptrHeadEnd;
	CHARPTR ptrContLen;

	int read=0;
	int bytes;

	//	1st read headers
	while(true){

		//	Wait
		if(!waitForEvent(link,10000)){

			content.strcpy(headers);
			return read > 0;
		}
				
		//	Read next lot
		if((bytes = recvTcp(link,&headers[read],size-read)) <= 0)
			return false;

		read+=bytes;
		headers[read]=0;
	
		//	Check for header & body
		ptrHeadEnd=strstr(headers,"\r\n\r\n");
		
		//	No header yet
		if(ptrHeadEnd)
			break;
	}

	ptrContLen=strstr(headers,"Content-Length: ");
	int contentLength;

	//	Terminate
	*ptrHeadEnd=0;

	//	Header & nobody - copy headers
	if(!ptrContLen){

		//	Just keep reading until server closes connection
		contentLength=128000;
		content.strcpy(headers);
	}
	else{

		//	Get content length
		if(!strparse(ptrContLen,"Content-Length: %1d",&contentLength))
			return false;

		//	Skip to start of body
		ptrHeadEnd += strlen("\r\n\r\n");
		content.strcpy(ptrHeadEnd);
	}

	//	Calculate remaining
	read = strlen(ptrHeadEnd);

	while(read < contentLength){
		
		//	Read next lot
		if((bytes = recvTcp(link,buffer,CBUFF_HUGE)) <= 0){

			switch(bytes){

				//	Remote closure
				case 0:
				return true;

			 	// Error - check
				default:
				switch(OSALASTERROR){

					//	No data to read - try again
		 			case OSAWOULDBLOCK:

						if(!waitForEvent(link,2000))
							return false;
			 
 					continue;

					// Oh oh
		 			default:
					return false;
				}
				break;
			}
		}

		buffer[bytes] = 0;
		read+=bytes;

		content.strcat(buffer);
	}

	//	Good to go
	return true;
}