手写精简版TinyHttpd项目(二)

在上一章中,我们基本完了socket通信的建立和消息的处理,那么这一章我们就来看如何生成一个静态的网页。

1.新建网页

        首先我们再代码的同级目录下新建一个index.html文件(当然也可以自己选择一个路径)然后将

如下的代码复制到新建的index.html中:




    
    

结果如下:

        手写精简版TinyHttpd项目(二)_第1张图片

2.显示静态网页。

        我们现在已经有了一个本地的网页,接下来我们就只需要在合适的时候将其显示再网页上计科。在我TinyHttpd精读中也提到了如何去显示一个静态网页--读取本地的文件,将其内容传递到客户端(网页)即可。思路主体就是这样,那么我们就来看我们的代码如何实现的:

void saver_file(int client_id){
    std::cout<<"saver_file\n";
    char buffer[1024] = {0};
    std::string file_name = "index.html";
    std::string path = "./";
    std::fstream file(path+file_name);
    std::string line = "";
    if(file.is_open()){
        std::string new_line = "";
        while(std::getline(file,new_line)){
            line = line + new_line;
            new_line = "";
        }
        send(client_id,line.c_str(),line.length(),0);
        file.close();
    }else{
        printf("con't open file maybe path is error\n");
        not_found(client_id);
    }
    //close(client_id);
    return ;
}

2.1not_found函数

        这个函数主要就是在网页上显示not_found的信息。可以直接照抄TinyHttpd的代码:

void not_found(int client)
{
 char buf[1024];
 sprintf(buf, "HTTP/1.0 404 NOT FOUND\r\n");
 send(client, buf, strlen(buf), 0);
 sprintf(buf, SERVER_STRING);
 send(client, buf, strlen(buf), 0);
 sprintf(buf, "Content-Type: text/html\r\n");
 send(client, buf, strlen(buf), 0);
 sprintf(buf, "\r\n");
 send(client, buf, strlen(buf), 0);
  //以下开始是body
 sprintf(buf, "Not Found\r\n");
 send(client, buf, strlen(buf), 0);
 sprintf(buf, "

The server could not fulfill\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "your request because the resource specified\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "is unavailable or nonexistent.\r\n"); send(client, buf, strlen(buf), 0); sprintf(buf, "\r\n"); send(client, buf, strlen(buf), 0); }

2.2head函数

        那么现在至此,我们还差最后一步就能显示一个静态网页了,那就是上一章我们代码中写到但是没有着重提到的响应头文件(headers函数),没有这个文件我们是无法显示静态网页的,所以这个文件比较重要,具体代码如下:

void headers(int client)
{
 char buf[1024];

 strcpy(buf, "HTTP/1.0 200 OK\r\n");
 send(client, buf, strlen(buf), 0);
 strcpy(buf, SERVER_STRING);
 send(client, buf, strlen(buf), 0);
 sprintf(buf, "Content-Type: text/html\r\n");
 send(client, buf, strlen(buf), 0);
 strcpy(buf, "\r\n");
  //以下开始是body
 send(client, buf, strlen(buf), 0);
}

 那么至此,把我们上述中的代码都写完后,我们就能显示静态网页了。(执行make,./service 然后网页输入localhost:8008)

我们将在下一章去实现一个动态网页。

你可能感兴趣的:(服务器,c++,websocket)