Example #1
0
void *run(void *argument){

	int client_fd;
	char buffer[1024];
	int n;
	
	bzero(buffer,1024);
	client_fd = * (int *)argument;
	bool alive = true;

	cout << "New Thread Started With Client FD: " << client_fd << endl << endl;

	while ( (n = read(client_fd,buffer,1024)) > -1 ){

		if( n > 0){
			cout << "Request from Client: " << endl << buffer << endl;
			
			HTTP* http = new HTTP();
			string response_string;
			if( http->parse_request(buffer) ){
				
				// Success Parsing the request
				if(http->connection.compare(CLOSE) == 0){
					alive = false;
				}

				response_string = get_response_stream(http);

			}else{

				// Failure Parsing the request
				response_string = http->prepare_response(BD,"",false);
				alive = false;
			}

			write(client_fd,response_string.c_str(),response_string.length());

			bzero(buffer,1024);

		}

		if(!alive){
			cout << "Thread with client FD closed: " << client_fd << endl;
			break;
		}

	}

	if ( n < 0){
		cerr << "Abrupt Close of Client Socket" << endl;
		exit(5);
	}
	cout << "Client Socket FD closed" << endl;
	close(client_fd);
}