单片机技术网|技术阅读
登录|注册

您现在的位置是:单片机技术网 > 技术阅读 > 分享一个超迷你的 web server

分享一个超迷你的 web server

点击上方「嵌入式大杂烩」,选择「置顶公众号」第一时间查看嵌入式笔记!

0. 什么是 web server?

web server 有两个意思:

  • 一台负责提供网页的主机,它通过 http 协议将网页等数据传给客户端(一般是浏览器);

  • 一个提供网页的服务器程序,例如 Apache / Nginix / lighttped 等;

  • 1. Tinyhttpd 简介

    开源项目 Tinyhttpd ( 6K star / 2.8K fork):

    官网:

    • https://sourceforge.net/projects/tinyhttpd/

    github mirror:

    • https://github.com/EZLippi/Tinyhttpd

    中文注释代码:

    • https://github.com/cbsheng/tinyhttpd

    Tinyhttpd 是一个 C 语言编写、极度简陋的 web 服务器,也可以叫 http 服务器。

    它的作用仅仅是用于学习 http 协议和 UNIX 系统调用, 不能用于生产环境中。

    虽然它没有任何商业价值,但是非常适合用来了解 WEB 服务器的基础知识。

    我们可以用它作为我们学习 Mpjg-streamer / Nginx/ Lighttpd 等更 复杂和更优秀开源项目的跳板。

    2. 编译运行

    编译运行:

    $ git clone https://github.com/EZLippi/Tinyhttpd
    $ cd tinyhttpd-0.1.0
    $ make
    $ ./httpd 
    httpd running on port 4000

    用浏览器访问:

    点击查看大图

    用命令访问:

  • 使用 netstat 查看 tinyhttpd 的网络状态:
  • $ netstat -ant | grep 4000
    tcp        0      0 0.0.0.0:4000            0.0.0.0:*               LISTEN 
  • 使用 nc 连接 tinyhttpd,并手动发送 http 请求:
  • $ nc 127.0.0.1 4000
    GET /index.html HTTP/1.1   // 输入 http 请求

    HTTP/1.0 200 OK            // 接收到 http 响应
    Server: es-hacker-httpserver
    Content-Type: text/html

    <HTML>
    <TITLE>Index</TITLE>
    <BODY>
    <H1>This is a simple webserver
    </BODY>
    </HTML>
  • 使用 curl 给 tinyhttpd 发送 http 请求:
  • $ curl localhost:4000/index.html
    <HTML>
    <TITLE>Index</TITLE>
    <BODY>
    <H1>This is a simple webserver
    </BODY>
    </HTML>

    使用 wireshark 抓包:

    点击查看大图

    (1) 浏览器:“请给我 ××× 网页的数据。”

    (2) web 服务器:“好的,这就是你要的数据。”

    3. 了解一下内部实现

    3.1 关于 web server 的入门知识

    web server 和 http 协议在整个网络传输中的位置:

    点击查看大图

    web server 处理请求的步骤:

    详细一点的步骤:

    点击查看大图
    • 建立连接——接受一个客户端连接;
    • 接收请求——从网络中读取一条 http 请求报文;
    • 处理请求——对请求报文进行解析;
    • 访问资源——访问报文中指定的资源;
    • 构建响应——创建带有正确首部的 http 响应报文;
    • 发送响应——将响应回送给客户端;

    什么是 http 报文?

    • http 报文是符合 http 协议的文本数据块;

    • 2 种类型:请求报文和响应报文;

    • 请求/响应报文由以下内容组成:

      • 请求行 或状态码行
      • 头字段
      • 空行
      • 可选的报文主体数据

    请求行中的方法字段:

    http 协议定义了客户端和服务器之间交互的消息内容和步骤,其基本思路非常简单。

    首先,客户端会向服务器发送请求消息请求消息中包含的内容是 "对什么" 和 "进行怎样的操作" 两个部分。

    其中 "对什么" 的部分就是 URI (Uniform Resource Identifier,统一资源标识符),一般就是网页或者文件或者程序等,而 "进行怎样的操作" 的部分称为方法,包括:

    点击查看大图

    3.2 Tinyhttpd 的内部实现

    分解 httpd.c:

    void accept_request(void *arg) 
    void bad_request(int client) 
    void cat(int client, FILE *resource) 
    void cannot_execute(int client) 
    void error_die(const char *sc) 
    void execute_cgi(int client, const char *path, 
    int get_line(int sock, char *buf, int size) 
    void headers(int client, const char *filename) 
    void not_found(int client) 
    void serve_file(int client, const char *filename) 
    int startup(u_short *port) 
    void unimplemented(int client) 
    int main(void

    就13 个 函数,和一些宏定义,就没有其他内容了。

    程序入口:main()

    int main(void)
    {
        int client_sock = -1;
        pthread_t newthread;

        // 1. 创建 socket,并且等待连接
        int server_sock = startup(&port);

        while (1) {
            // 2. 接受连接
            client_sock = accept();

            // 3. 创建处理线程
            pthread_create(&newthread , 
                NULL
                (void *)accept_request, 
                ...)
        }
    }

    创建 socket: startup()

    int startup(u_short *port)
    {
        struct sockaddr_in name;

        // 1. 创建 webserver 端的 socket
        httpd = socket(PF_INET, SOCK_STREAM, 0);

        // 2. 初始化 webserver 的 ip 地址
        name.sin_family = AF_INET;
        name.sin_port = htons(*port);
        name.sin_addr.s_addr = htonl(INADDR_ANY);

        // 3. 绑定 webserver 的socket 和 ip 地址
        bind(httpd, (struct sockaddr *)&name, ...);

        // 4. 开始监听
        listen(httpd, 5);
    }

    没什么特别的,就是典型 tcp server 编程:

    解析 http 请求报文:accept_request()

    这里将会完成 web server 最核心的工作:

    • 读取/解析 http 请求报文,构建响应报文。
    void accept_request(void *arg)
    {
        // 1. 提取第一行数据
        numchars = get_line(client, buf, sizeof(buf));

        // 2. 从第一行数据中提取出 http 方法

        // 3. 处理 POST 方法

        // 4. 处理 GET 方法
        if (strcasecmp(method, "GET") == 0) {
            // 4.1 提取 URI
            while (...)
                query_string++;
        }

        // 5. 构建并发送 http 响应报文给客户端
        serve_file(client, path);
    }

    构建并发送 http 响应报文给客户端:serve_file()

    void serve_file(int client, const char *filename)
    {
        // 1. 打开 URI 指定的资源
        FILE *resource = fopen(filename, "r");

        // 2. 发送 响应报文的 header: HTTP/1.0 200 OK...
        headers(client, filename);

        // 3. 读取并发送资源给 客户端: fgets() ---> send()
        cat(client, resource);
    }

    到此,Tinyhttpd的核心实现就分析完了,更多的细节,请各位自行阅读源码吧~~~

    4. 相关参考

    • http 权威指南 / 第1~5章

    • Unix 网络编程 / 第1~5章

    • 网络是怎么连接的 / 第1、2、6章

    • 深入理解 Nginx 模块;

    • Lighttpd Documentation (https://redmine.lighttpd.net/projects/lighttpd/wiki/docs)

    温馨提示

    由于微信公众号近期改变了推送规则,如果您想经常看到我们的文章,可以在每次阅读后,在页面下方点一个「赞」或「在看」,这样每次推送的文章才会第一时间出现在您的订阅列表里。

    猜你喜欢:


    在公众号聊天界面回复1024,可获取嵌入式资源;回复 ,可查看文章汇总。

    文章都看完了不点个