依窗看雨 發表於 2024-8-22 12:11:02

如何搭建http的webserver服务器

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li><a href="#_label0">一、web服务器搭建过程</a></li><ul class="second_class_ul"><li><a href="#_lab2_0_0">1、配置web服务器</a></li><li><a href="#_lab2_0_1">2、 注册 URI处理器</a></li><li><a href="#_lab2_0_2">3、实现URI处理函数</a></li><li><a href="#_lab2_0_3">4、处理HTTP请求</a></li><li><a href="#_lab2_0_4">5、 发送响应</a></li></ul><li><a href="#_label1">二、主要使用API的说明</a></li><ul class="second_class_ul"></ul></ul></div><p>最近在使用ESP32搭建web服务器测试,发现esp32搭建这类开发环境还是比较方便的。具体的http协议这里就不再赘述,我们主要说一下如何使用ESP32提供的API来搭建我们的http web。</p>
<p class="maodian"><a name="_label0"></a></p><h2>一、web服务器搭建过程</h2>
<p class="maodian"><a name="_lab2_0_0"></a></p><h3>1、配置web服务器</h3>
<p>在<a href="https://so.csdn.net/so/search?q=ESP-IDF&spm=1001.2101.3001.7020" rel="external nofollow"target="_blank" title="ESP-IDF">ESP-IDF</a>中,Web服务器使用httpd组件实现。我们需要先创建httpd_config_t结构体,指定服务器的端口、最大并发连接数、URI匹配处理器等选项。然后,我们通过调用httpd_start函数来启动Web服务器。(使用默认的配置就可以,包括端口号都已经默认配置好了)</p>
<div class="jb51code"><pre class="brush:plain;">httpd_config_t config = HTTPD_DEFAULT_CONFIG();
httpd_handle_t server = NULL;
// 设置服务器端口为80
config.server_port = 80;
// 创建HTTP服务器句柄
if (httpd_start(&amp;server, &amp;config) != ESP_OK) {
    printf("Error starting server!\n");
    return;
}
</pre></div>
<p class="maodian"><a name="_lab2_0_1"></a></p><h3>2、 注册 URI处理器</h3>
<p>在Web服务器启动后,我们需要为不同的URI注册处理器函数。当Web服务器接收到请求时,会根据请求的URI选择相应的处理器函数进行处理。在ESP-IDF中,我们可以使用httpd_register_uri_handler函数注册URI处理器。该函数的原型如下</p>
<div class="jb51code"><pre class="brush:plain;">esp_err_t httpd_register_uri_handler(httpd_handle_t hd, const httpd_uri_t *uri)</pre></div>
<p>其中,hd参数为HTTP服务器句柄;uri参数为包含URI路径、HTTP方法、处理函数等信息的结构体指针。例如:</p>
<div class="jb51code"><pre class="brush:plain;">static const httpd_uri_t echo = {
    .uri       = "/",
    .method    = HTTP_POST,
    .handler   = echo_post_handler,
    .user_ctx= NULL
};
static esp_err_t echo_post_handler(httpd_req_t *req)
{
    char buf;
    // char ssid;
    // char pswd;
    int ret, remaining = req-&gt;content_len;
    while (remaining &gt; 0) {
      /* Read the data for the request */
      if ((ret = httpd_req_recv(req, buf,
                        MIN(remaining, sizeof(buf)))) &lt;= 0) {
            if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
                /* Retry receiving if timeout occurred */
                continue;
            }
            return ESP_FAIL;
      }
      /* Send back the same data */
      httpd_resp_send_chunk(req, buf, ret);
      remaining -= ret;
      esp_err_t e = httpd_query_key_value(buf,"ssid",wifi_name,sizeof(wifi_name));
      if(e == ESP_OK) {
            printf("ssid = %s\r\n",wifi_name);
      }
      else {
            printf("error = %d\r\n",e);
      }
      e = httpd_query_key_value(buf,"password",wifi_password,sizeof(wifi_password));
      if(e == ESP_OK) {
            printf("pswd = %s\r\n",wifi_password);
      }
      else {
            printf("error = %d\r\n",e);
      }
      /* Log data received */
      ESP_LOGI(TAG, "=========== RECEIVED DATA ==========");
      ESP_LOGI(TAG, "%.*s", ret, buf);
      ESP_LOGI(TAG, "====================================");
    }
    // End response
    httpd_resp_send_chunk(req, NULL, 0);
    if(strcmp(wifi_name ,"\0")!=0 &amp;&amp; strcmp(wifi_password,"\0")!=0)
    {
      xSemaphoreGive(ap_sem);
      ESP_LOGI(TAG, "set wifi name and password successfully! goto station mode");
    }
    return ESP_OK;
}</pre></div>
<p>html的网页如下:这个网页包含了按钮的定义,以及发送json格式的数据。</p>
<p>最后送json数据的时候,要用JSON.stringify方法格式化data,否则esp32解析json会报错,此处一定要注意!!!<br />整体html界面非常简单,没有基础的也很容易读懂,里面写了一个js函数,该函数是在点击按钮的时候触发,功能主要是读取文本框输入的数据,将数据封装为json格式,然后post发送数据,xhttp.open(&ldquo;POST&rdquo;, &ldquo;/wifi_data&rdquo;, true);中的url &ldquo;/wifi_data&rdquo;和esp32服务端中的定义要一致,否则是无法成功的。</p>
<div class="jb51code"><pre class="brush:xhtml;">&lt;!DOCTYPE html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Web server system&lt;/title&gt;
&lt;/head&gt;
&lt;table class="fixed" border="5"&gt;
    &lt;col width="1000px" /&gt;&lt;col width="500px" /&gt;
    &lt;tr&gt;&lt;td&gt;
      &lt;h2 style=" text-align:center;"&gt; **** Web Server ***&lt;/h2&gt;
      &lt;h3&gt;wifi 密码配置&lt;/h3&gt;
    &lt;div&gt;
      &lt;label for="name"&gt;wifi名称&lt;/label&gt;
      &lt;input type="text" id="wifi" name="car_name" placeholder="ssid"&gt;
      &lt;br&gt;
      &lt;label for="type"&gt;密码&lt;/label&gt;
      &lt;input type="text" id="code" name="car_type" placeholder="password"&gt;
      &lt;br&gt;
      &lt;button id ="send_WIFI" type="button" onclick="send_wifi()"&gt;提交&lt;/button&gt;
    &lt;/div&gt;
    &lt;/td&gt;&lt;td&gt;
      &lt;table border="10"&gt;
            &lt;tr&gt;
                &lt;td&gt;
                  &lt;label for="newfile"&gt;Upload a file&lt;/label&gt;
                &lt;/td&gt;
                &lt;td colspan="2"&gt;
                  &lt;input id="newfile" type="file" onchange="setpath()" style="width:100%;"&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;
                  &lt;label for="filepath"&gt;Set path on server&lt;/label&gt;
                &lt;/td&gt;
                &lt;td&gt;
                  &lt;input id="filepath" type="text" style="width:100%;"&gt;
                &lt;/td&gt;
                &lt;td&gt;
                  &lt;button id="upload" type="button" onclick="upload()"&gt;Upload&lt;/button&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
      &lt;/table&gt;
    &lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;
&lt;script&gt;
function setpath() {
    var default_path = document.getElementById("newfile").files.name;
    document.getElementById("filepath").value = default_path;
}
function upload() {
    var filePath = document.getElementById("filepath").value;
    var upload_path = "/upload/" + filePath;
    var fileInput = document.getElementById("newfile").files;
    /* Max size of an individual file. Make sure this
   * value is same as that set in file_server.c */
    var MAX_FILE_SIZE = 200*1024;
    var MAX_FILE_SIZE_STR = "200KB";
    if (fileInput.length == 0) {
      alert("No file selected!");
    } else if (filePath.length == 0) {
      alert("File path on server is not set!");
    } else if (filePath.indexOf(' ') &gt;= 0) {
      alert("File path on server cannot have spaces!");
    } else if (filePath == '/') {
      alert("File name not specified after path!");
    } else if (fileInput.size &gt; 200*1024) {
      alert("File size must be less than 200KB!");
    } else {
      document.getElementById("newfile").disabled = true;
      document.getElementById("filepath").disabled = true;
      document.getElementById("upload").disabled = true;
      var file = fileInput;
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4) {
                if (xhttp.status == 200) {
                  document.open();
                  document.write(xhttp.responseText);
                  document.close();
                } else if (xhttp.status == 0) {
                  alert("Server closed the connection abruptly!");
                  location.reload()
                } else {
                  alert(xhttp.status + " Error!\n" + xhttp.responseText);
                  location.reload()
                }
            }
      };
      xhttp.open("POST", upload_path, true);
      xhttp.send(file);
    }
}
function send_wifi() {
    var input_ssid = document.getElementById("wifi").value;
    var input_code = document.getElementById("code").value;
    var xhttp = new XMLHttpRequest();
      xhttp.open("POST", "/wifi_data", true);
      xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4) {
                if (xhttp.status == 200) {
                  console.log(xhttp.responseText);
                } else if (xhttp.status == 0) {
                  alert("Server closed the connection abruptly!");
                  location.reload()
                } else {
                  alert(xhttp.status + " Error!\n" + xhttp.responseText);
                  location.reload()
                }
            }
      };
    var data = {
      "wifi_name":input_ssid,
      "wifi_code":input_code
    }
      xhttp.send(JSON.stringify(data));
}
&lt;/script&gt;</pre></div>
<div class="jb51code"><pre class="brush:js;">static esp_err_t html_default_get_handler(httpd_req_t *req)
{
    // /* Send HTML file header */
    // httpd_resp_sendstr_chunk(req, "&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;body&gt;");
    /* Get handle to embedded file upload script */
    extern const unsigned char upload_script_start[] asm("_binary_upload_script_html_start");
    extern const unsigned char upload_script_end[] asm("_binary_upload_script_html_end");
    const size_t upload_script_size = (upload_script_end - upload_script_start);
    /* Add file upload form and script which on execution sends a POST request to /upload */
    httpd_resp_send_chunk(req, (const char *)upload_script_start, upload_script_size);
    /* Send remaining chunk of HTML file to complete it */
    httpd_resp_sendstr_chunk(req, "&lt;/body&gt;&lt;/html&gt;");
    /* Send empty chunk to signal HTTP response completion */
    httpd_resp_sendstr_chunk(req, NULL);
    return ESP_OK;
}
    httpd_uri_t html_default = {
      .uri = "/", // Match all URIs of type /path/to/file
      .method = HTTP_GET,
      .handler = html_default_get_handler,
      .user_ctx = "html" // Pass server data as context
    };
    httpd_register_uri_handler(server, &amp;html_default);</pre></div>
<p><strong>这里要特别注意:</strong></p>
<p><strong>1)、.uri = &quot;/&quot;,这个表示当你打开网页的IP地址后第一个要显示的页面,也就是要放到根目录下(&quot;/&quot;也就是根目录)。</strong></p>
<p><strong>2)、ESP32可以直接将html的网页编译进来不需要转为数组,但在</strong><strong>CMakeList.txt文件中需要EMBED_FILES upload_script.html</strong>这样的形式引入网页文件。这个html编译出出来的文本文件怎么使用呢。wifi.html编译出来一般名称是默认的_binary_名称_类型_start。这个指针代编译出来文件的起始地址。_binary_名称_类型_end,代表结束地址。wifi.html的引用方式如下。通过以下的方式就可以获得html这个大数组。</p>
<div class="jb51code"><pre class="brush:plain;">    extern const unsigned char upload_script_start[] asm("_binary_upload_script_html_start");
    extern const unsigned char upload_script_end[] asm("_binary_upload_script_html_end");
    const size_t upload_script_size = (upload_script_end - upload_script_start);
    /* Add file upload form and script which on execution sends a POST request to /upload */
    httpd_resp_send_chunk(req, (const char *)upload_script_start, upload_script_size);</pre></div>
<p class="maodian"><a name="_lab2_0_2"></a></p><h3>3、实现URI处理函数</h3>
<p>在注册URI处理器后,我们需要实现对应的处理器函数。URI处理器函数的原型为:</p>
<div class="jb51code"><pre class="brush:plain;">typedef esp_err_t (*httpd_uri_func_t)(httpd_req_t *req);
</pre></div>
<p>如上面示例中的:</p>
<div class="jb51code"><pre class="brush:plain;">static esp_err_t html_default_get_handler(httpd_req_t *req)</pre></div>
<p class="maodian"><a name="_lab2_0_3"></a></p><h3>4、处理HTTP请求</h3>
<p>在URI处理器函数中,我们可以通过HTTP请求信息结构体指针httpd_req_t获取HTTP请求的各种参数和数据。以下是一些常用的HTTP请求处理函数:</p>
<p>httpd_req_get_hdr_value_str:获取HTTP请求头中指定字段的值(字符串格式)<br />httpd_req_get_url_query_str:获取HTTP请求URL中的查询参数(字符串格式)<br />httpd_query_key_value:解析HTTP请求URL中的查询参数,获取指定参数名的值(字符串格式)<br />httpd_req_recv:从HTTP请求接收数据<br />httpd_req_send:发送HTTP响应数据<br />httpd_resp_set_type:设置HTTP响应内容的MIME类型<br />httpd_resp_send_chunk:分块发送HTTP响应数据。<br />例如,以下是一个URI处理器函数的示例,用于处理/echo路径的POST请求:</p>
<div class="jb51code"><pre class="brush:plain;">static esp_err_t echo_post_handler(httpd_req_t *req)
{
    char buf;
    int ret, remaining = req-&gt;content_len;
    // 从HTTP请求中接收数据
    while (remaining &gt; 0) {
      ret = httpd_req_recv(req, buf, MIN(remaining, sizeof(buf)));
      if (ret &lt;= 0) {
            if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
                // 处理超时
                httpd_resp_send_408(req);
            }
            return ESP_FAIL;
      }
      // 处理接收到的数据
      // ...
      remaining -= ret;
    }
    // 发送HTTP响应
    httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
    httpd_resp_send(req, "Received data: ", -1);
    httpd_resp_send_chunk(req, buf, req-&gt;content_len);
    httpd_resp_send_chunk(req, NULL, 0);
    return ESP_OK;
}
</pre></div>
<p class="maodian"><a name="_lab2_0_4"></a></p><h3>5、 发送响应</h3>
<p>在URI处理函数中,可以使用httpd_resp_send()函数将响应发送回客户端。该函数需要传入一个httpd_req_t结构体作为参数,该结构体表示HTTP请求和响应。</p>
<p>例如,在上面的hello_get_handler处理函数中,可以使用httpd_resp_send()函数将&ldquo;Hello, World!&rdquo;字符串作为响应发送回客户端:</p>
<div class="jb51code"><pre class="brush:plain;">static esp_err_t hello_get_handler(httpd_req_t *req)
{
    const char* resp_str = "Hello, World!";
    httpd_resp_send(req, resp_str, strlen(resp_str));
    return ESP_OK;
}</pre></div>
<p class="maodian"><a name="_label1"></a></p><h2>二、主要使用API的说明</h2>
<p><strong>1. httpd_register_uri_handler</strong><br />用于将HTTP请求的URI路由到处理程序。这个函数接收两个参数:httpd_handle_t类型的HTTP服务器句柄和httpd_uri_t类型的URI配置。</p>
<p><strong>2. httpd_handle_t</strong><br />httpd_handle_t是HTTP服务器的一个句柄,它是通过httpd_start函数创建的。而httpd_uri_t则定义了HTTP请求的URI信息,包括URI路径、HTTP请求方法和处理函数等。</p>
<p><strong>3. httpd_query_key_value获取变量值</strong><br />httpd_query_key_value 用于从查询字符串中获取指定键的值。查询字符串是指URL中?后面的部分,包含多个键值对,每个键值对之间使用&amp;分隔。例如,对于以下URL:<br />http://192.168.1.1/path/to/handler?key1=value1&amp;key2=value2<br />获取其中的:<br />esp_err_t httpd_query_key_value(const char *query, const char *key, char *buf, size_t buf_len);</p>
<p>这是一个使用示例</p>
<div class="jb51code"><pre class="brush:plain;">char query_str[] = "key1=value1&amp;key2=value2";
char key[] = "key1";
char value;
if (httpd_query_key_value(query_str, key, value, sizeof(value)) == ESP_OK) {
    printf("value=%s\n", value);
} else {
    printf("key not found\n");
}
</pre></div>
<p>4. 获取get参数示例</p>
<p>下面定义的 handler 演示了如何从请求参数里解析 字符串param1和整型变量param2:</p>
<div class="jb51code"><pre class="brush:plain;"> esp_err_t index_handler(httpd_req_t *req)
{
   char* query_str = NULL;
   char param1_value = {0};
   int param2_value=0;
   query_str = strstr(req-&gt;uri, "?");
   if(query_str!=NULL){
         query_str ++;
         httpd_query_key_value(query_str, "param1", param1_value, sizeof(param1_value));
         char param2_str = {0};
         httpd_query_key_value(query_str, "param2", param2_str, sizeof(param2_str));
         param2_value = atoi(param2_str);
   }
   char resp_str = {0};
   snprintf(resp_str, sizeof(resp_str), "param1=%s, param2=%d", param1_value, param2_value);
    httpd_resp_send(req, resp_str, strlen(resp_str));
    return ESP_OK;
}</pre></div>
<p>5. 获取post参数示例</p>
<p>下面的示例代码中根据httpd_req_t的content_len来分配一个缓冲区,并解析请求中的POST参数:</p>
<div class="jb51code"><pre class="brush:plain;">
esp_err_t post_demo_handler(httpd_req_t *req)
{
    char post_string;
    int post_int=0;
    if (req-&gt;content_len &gt; 0)
    {
      // 从请求体中读取POST参数
      char *buf = malloc(req-&gt;content_len + 1);
      int ret = httpd_req_recv(req, buf, req-&gt;content_len);
      if (ret &lt;= 0)
      {
            // 接收数据出错
            free(buf);
            return ESP_FAIL;
      }
      buf = '\0';
      // 解析POST参数
      char *param_str;
      param_str = strtok(buf, "&amp;");
      while (param_str != NULL)
      {
            char *value_str = strchr(param_str, '=');
            if (value_str != NULL)
            {
                *value_str++ = '\0';
                if (strcmp(param_str, "post_string") == 0)
                {
                  strncpy(post_string, value_str, sizeof(post_string));
                }
                else if (strcmp(param_str, "post_int") == 0)
                {
                  post_int = atoi(value_str);
                }
            }
            param_str = strtok(NULL, "&amp;");
      }
      free(buf);
    }
    // 将结果打印输出
    printf("post_string=%s, post_int=%d\n", post_string, post_int);
    // 返回成功
    httpd_resp_send(req, NULL, 0);
    return ESP_OK;
}
httpd_uri_t post_uri = {
         .uri = "/post",
         .method = HTTP_POST,
         .handler = post_demo_handler,
         .user_ctx = NULL
};</pre></div>
<p>到此这篇关于搭建http的webserver的服务器的文章就介绍到这了,更多相关http的webserver服务器内容请搜索琼殿技术社区以前的文章或继续浏览下面的相关文章希望大家以后多多支持琼殿技术社区!</p>
頁: [1]
查看完整版本: 如何搭建http的webserver服务器