
目录
我们之前通过管道子进程,把对应文件的信息读取上来,直接返回回去不就行了吗,其实并不是这样的,我们读取上来的只是正文的部分,其相应行依然需要我们来自己构建。
但是现在又有一个问题,就是我们对于合法的请求,找到对应的文件,构建请求成功(OK)的响应,但是对于请求过程中发生错误的时候,我们应该如何构建相应的相应呢?——也是根据其错误类型构建相应处理结果的相应。
- #define OK 200
- #define BAD_REQUEST 400
- #define NOT_FOUND 404
- #define SERVER_ERROR 500
-
- void BuildHttpResponseHelper()
- {
- //http_request;
- //http_response;
- auto &code = http_response.status_code;
- //构建状态行
- auto &status_line = http_response.status_line;
- status_line += HTTP_VERSION;
- status_line += " ";
- status_line += std::to_string(code);
- status_line += " ";
- status_line += Code2Desc(code);
- status_line += LINE_END;
-
- //构建响应正文,可能包括响应报头
- std::string path = WEB_ROOT;
- path += "/";
- switch(code){
- case OK:
- BuildOkResponse();
- break;
- case NOT_FOUND:
- path += PAGE_404;
- HandlerError(path);
- break;
- case BAD_REQUEST:
- path += PAGE_404;
- HandlerError(path);
- break;
- case SERVER_ERROR:
- path += PAGE_404;
- HandlerError(path);
- break;
- // case 500:
- // HandlerError(PAGE_500);
- // break;
- default:
- break;
- }
- }
1.我们先构建状态行,包括版本号,状态码已经状态码的描述,将这三者加入到我们状态行之中。
2. 在之前,我们的错误都是统一按照404处理了,而现在我们需要进行错误处理,所以我们需要把所有的错误分开来看,比如新加入400(页面域名不存在或者请求错误),500(服务器内部错误)等待,我们根据相关的错误码,返回对应的错误网页。
- void BuildOkResponse()
- {
- std::string line = "Content-Type: ";
- line += Suffix2Desc(http_request.suffix);
- line += LINE_END;
- http_response.response_header.push_back(line);
-
- line = "Content-Length: ";
- if(http_request.cgi){
- line += std::to_string(http_response.response_body.size());
- }
- else{
- line += std::to_string(http_request.size); //Get
- }
- line += LINE_END;
- http_response.response_header.push_back(line);
- }
假设现在请求是成功的,那么我们就构建成功的相应,我们通过之前截取的文件类型加入到文件类型中来,然后插入请求方法这个内容中,之后再加入文件长度的属性,如果是cgi,那么取正文的个数属性size,如果不是cgi,那么就返回当时请求读取的数据(静态网页)的数据,再插入到请求内容之中。
- void HandlerError(std::string page)
- {
- std::cout << "debug: " << page << std::endl;
- http_request.cgi = false;
- //要给用户返回对应的404页面
- http_response.fd = open(page.c_str(), O_RDONLY);
- if(http_response.fd > 0){
- struct stat st;
- stat(page.c_str(), &st);
- http_request.size = st.st_size;
-
- std::string line = "Content-Type: text/html";
- line += LINE_END;
- http_response.response_header.push_back(line);
-
- line = "Content-Length: ";
- line += std::to_string(st.st_size);
- line += LINE_END;
- http_response.response_header.push_back(line);
- }
- }
有可能在cgi之前发生了错误,这个时候就直接返回错误网页就可以了,所以先将cgi改为false,然后打开对应的404的错误网页,然后通过之前讲过的用stat来获取资源的大小,将其填充到请求大小以及返回报文的大小。
为了能够及时的把错误进行处理,我们可以从读取分析请求报文开始所有过程中可能遇到的错误用相关的错误码进行分离然后进行相关的处理。
我们设置一个stop,然后将处理分析报文函数都设置成stop的布尔值,当stop=1的时候,表明此时不再需要读取。
- class EndPoint{
- private:
- int sock;
- HttpRequest http_request;
- HttpResponse http_response;
- bool stop;
- private:
- bool RecvHttpRequestLine()
- {
- auto &line = http_request.request_line;
- if(Util::ReadLine(sock, line) > 0){
- line.resize(line.size()-1);
- LOG(INFO, http_request.request_line);
- }
- else{
- stop = true;
- }
- std::cout << "RecvHttpRequestLine: " << stop << std::endl;
- return stop;
- }
- bool RecvHttpRequestHeader()
- {
- std::string line;
- while(true){
- line.clear();
- if(Util::ReadLine(sock, line) <= 0){
- stop = true;
- break;
- }
- if(line == "\n"){
- http_request.blank = line;
- break;
- }
- line.resize(line.size()-1);
- http_request.request_header.push_back(line);
- LOG(INFO, line);
- }
- std::cout <<"stop debug: " << stop << std::endl;
- return stop;
- }
- void ParseHttpRequestLine()
- {
- auto &line = http_request.request_line;
- std::stringstream ss(line);
- ss >> http_request.method >> http_request.uri >> http_request.version;
- auto &method = http_request.method;
- std::transform(method.begin(), method.end(), method.begin(), ::toupper);
- }
- void ParseHttpRequestHeader()
- {
- std::string key;
- std::string value;
- for(auto &iter : http_request.request_header)
- {
- if(Util::CutString(iter, key, value, SEP)){
- http_request.header_kv.insert({key, value});
- }
- }
- }
-
- bool IsNeedRecvHttpRequestBody()
- {
- auto &method = http_request.method;
- if(method == "POST"){
- auto &header_kv = http_request.header_kv;
- auto iter = header_kv.find("Content-Length");
- if(iter != header_kv.end()){
- LOG(INFO, "Post Method, Content-Length: "+iter->second);
- http_request.content_length = atoi(iter->second.c_str());
- return true;
- }
- }
- return false;
- }
-
- bool RecvHttpRequestBody()
- {
- if(IsNeedRecvHttpRequestBody()){
- int content_length = http_request.content_length;
- auto &body = http_request.request_body;
-
- char ch = 0;
- while(content_length){
- ssize_t s = recv(sock, &ch, 1, 0);
- if(s > 0){
- body.push_back(ch);
- content_length--;
- }
- else{
- stop = true;
- break;
- }
- }
- LOG(INFO, body);
- }
- return stop;
- }
-
-
-
- void RecvHttpRequest()
- {
- // || 短路求值
- if( (!RecvHttpRequestLine()) && (!RecvHttpRequestHeader()) ){
- ParseHttpRequestLine();
- ParseHttpRequestHeader();
- RecvHttpRequestBody();
- }
- }
-
-
-
-
- ep->RecvHttpRequest();
- if(!ep->IsStop()){ //一定要注意逻辑关系
- LOG(INFO, "Recv No Error, Begin Build And Send");
- ep->BuildHttpResponse();
- ep->SendHttpResponse();
- }
- else{
- LOG(WARNING, "Recv Error, Stop Build And Send");
- }
我们分析的时候也是一样的,利用短路求值的方法,只有当接收请求行以及接收请求方法都正确的时候,我们才会进行分析请求行和请求方法,如果在接收的出现错误 stop作为返回值直接就会被置为1,这个时候不会再进行分析,直接跳出,而当程序运行到后面检测到stop为1,此时会直接报错返回,不会在进行后续处理。
为了进一步使用线程池来进行多线程调用的问题,我们现在就完成封装一下回调函数,当有线程接收到任务的时候就需要进行调用回调函数进行处理,我们只需要把之前的代码进行一下修改即可。
- class CallBack{
- public:
- CallBack()
- {}
- void operator()(int sock)
- {
- HandlerRequest(sock);
- }
- void HandlerRequest(int sock)
- {
- LOG(INFO, "Hander Request Begin");
- #ifdef DEBUG
- //For Test
- char buffer[4096];
- recv(sock, buffer, sizeof(buffer), 0);
- std::cout << "-------------begin----------------" << std::endl;
- std::cout << buffer << std::endl;
- std::cout << "-------------end----------------" << std::endl;
- #else
- EndPoint *ep = new EndPoint(sock);
- ep->RecvHttpRequest();
- if(!ep->IsStop()){ //一定要注意逻辑关系
- LOG(INFO, "Recv No Error, Begin Build And Send");
- ep->BuildHttpResponse();
- ep->SendHttpResponse();
- }
- else{
- LOG(WARNING, "Recv Error, Stop Build And Send");
- }
- delete ep;
- #endif
- LOG(INFO, "Hander Request End");
- }
- ~CallBack()
- {}
- };
- #pragma once
-
- #include
- #include "Protocol.hpp"
-
- class Task{
- private:
- int sock;
- CallBack handler; //设置回调
- public:
- Task()
- {}
- Task(int _sock):sock(_sock)
- {}
- //处理任务
- void ProcessOn()
- {
- handler(sock);
- }
- ~Task()
- {}
- };
之前在别的章节里面有完整解释过线程池,在这里就不过多解释了,直接上代码。
- #pragma once
-
- #include
- #include
- #include
- #include "Log.hpp"
- #include "Task.hpp"
-
- #define NUM 6
-
- class ThreadPool{
- private:
- int num;
- bool stop;
- std::queue
task_queue; - pthread_mutex_t lock;
- pthread_cond_t cond;
-
- ThreadPool(int _num = NUM):num(_num),stop(false)
- {
- pthread_mutex_init(&lock, nullptr);
- pthread_cond_init(&cond, nullptr);
- }
- ThreadPool(const ThreadPool &){}
-
- static ThreadPool *single_instance;
- public:
- static ThreadPool* getinstance()
- {
- static pthread_mutex_t _mutex = PTHREAD_MUTEX_INITIALIZER;
- if(single_instance == nullptr){
- pthread_mutex_lock(&_mutex);
- if(single_instance == nullptr){
- single_instance = new ThreadPool();
- single_instance->InitThreadPool();
- }
- pthread_mutex_unlock(&_mutex);
- }
- return single_instance;
- }
-
- bool IsStop()
- {
- return stop;
- }
- bool TaskQueueIsEmpty()
- {
- return task_queue.size() == 0 ? true : false;
- }
- void Lock()
- {
- pthread_mutex_lock(&lock);
- }
- void Unlock()
- {
- pthread_mutex_unlock(&lock);
- }
- void ThreadWait()
- {
- pthread_cond_wait(&cond, &lock);
- }
- void ThreadWakeup()
- {
- pthread_cond_signal(&cond);
- }
- static void *ThreadRoutine(void *args)
- {
- ThreadPool *tp = (ThreadPool*)args;
-
- while(true){
- Task t;
- tp->Lock();
- while(tp->TaskQueueIsEmpty()){
- tp->ThreadWait(); //当我醒来的时候,一定是占有互斥锁的!
- }
- tp->PopTask(t);
- tp->Unlock();
- t.ProcessOn();
- }
- }
- bool InitThreadPool()
- {
- for(int i = 0; i < num; i++){
- pthread_t tid;
- if( pthread_create(&tid, nullptr, ThreadRoutine, this) != 0){
- LOG(FATAL, "create thread pool error!");
- return false;
- }
- }
- LOG(INFO, "create thread pool success!");
- return true;
- }
- void PushTask(const Task &task) //in
- {
- Lock();
- task_queue.push(task);
- Unlock();
- ThreadWakeup();
- }
- void PopTask(Task &task) //out
- {
- task = task_queue.front();
- task_queue.pop();
- }
- ~ThreadPool()
- {
- pthread_mutex_destroy(&lock);
- pthread_cond_destroy(&cond);
- }
- };
-
- ThreadPool* ThreadPool::single_instance = nullptr;
- #include
- #include
- #include "comm.hpp"
- #include "mysql.h"
-
- bool InsertSql(std::string sql)
- {
- MYSQL *conn = mysql_init(nullptr);
- mysql_set_character_set(conn, "utf8");
- if(nullptr == mysql_real_connect(conn, "127.0.0.1", "http_test", "12345678", "http_test", 3306, nullptr, 0)){
- std::cerr << "connect error!" << std::endl;
- return 1;
- }
- std::cerr << "connect success" << std::endl;
-
- std::cerr << "query : " << sql <
- int ret = mysql_query(conn, sql.c_str());
- std::cerr << "result: " << ret << std::endl;
- mysql_close(conn);
- return true;
- }
-
- int main()
- {
- std::string query_string;
- //from http
- if(GetQueryString(query_string)){
- std::cerr << query_string << std::endl;
- //数据处理?
- //name=tom&passwd=111111
-
- std::string name;
- std::string passwd;
-
- CutString(query_string, "&", name, passwd);
-
- std::string _name;
- std::string sql_name;
- CutString(name, "=", _name, sql_name);
-
- std::string _passwd;
- std::string sql_passwd;
- CutString(passwd, "=", _passwd, sql_passwd);
-
- std::string sql = "insert into user(name, passwd) values (\'";
- sql += sql_name;
- sql += "\',\'";
- sql += sql_passwd;
- sql += "\')";
-
- //插入数据库
- if(InsertSql(sql)){
- std::cout << "";
- std::cout << "";
- std::cout << "
注册成功!
"; - }
- }
- return 0;
- }