ESP32-Web-Server编程-建立多个 web server

ESP32-Web-Server编程-建立多个 web server

概述

当一个 web server 处理的请求过多、或者有长时间占用此 web server 的使用场景时,一个 web server 就不够用了。

这种情况下,我们可以在一个设备上建立两个或多个 web server 来满足更复杂的需求。

单个设备上建立多个 web server 的方法有多种,这里介绍最简单的一种-通过新建一个 Web Port 来新增一个 Web server。

回顾 HTTP 协议

如前述博客 ESP32-Web-Server编程-建立第一个网页 介绍的那样,HTTP 协议是基于 TCP 传输的互联网协议,默认的 TCP 端口号是 80,当我们输入 https://www.baidu.com时,它会向 Web 的默然端口号80 https://www.baidu.com:80 发起访问。如果 Web 服务器在 81 端口也可以正常响应,那么我们可以输入 https://www.baidu.com:81来访问 81 端口的服务器。

### ESP32 Web Server Example Code and Documentation For developing a web server on the ESP32, one can utilize the Arduino framework or Espressif's IoT Development Framework (ESP-IDF). Below is an example using the Arduino environment which simplifies many aspects of development including setting up network connections. #### Setting Up Environment To begin with, ensure that the ESP32 board support package has been added within the Arduino IDE preferences. This allows access to libraries specifically designed for this microcontroller family[^1]. #### Basic HTTP Web Server Implementation A simple implementation involves creating an instance of `WebServer` class specifying port number typically 80 for HTTP services: ```cpp #include <WiFi.h> #include <WebServer.h> const char* ssid = "your_SSID"; const char* password = "your_PASSWORD"; WebServer server(80); void handleRoot() { String htmlPage = "<html><body>"; htmlPage += "<h1>Hello from ESP32</h1>"; htmlPage += "</body></html>"; server.send(200, "text/html", htmlPage); } void setup(){ Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED){ delay(1000); Serial.println("Connecting..."); } Serial.print("Connected to "); Serial.println(WiFi.localIP()); server.on("/", handleRoot); server.begin(); } void loop(){ server.handleClient(); } ``` This sketch connects the device to Wi-Fi and sets up a basic HTML response when accessing root URL path "/". The IP address assigned by DHCP will be printed out over serial console once connected successfully. #### Advanced Features Using Libraries More complex functionalities such as serving files stored in SPIFFS flash file system or handling POST requests could also be implemented easily thanks to available third-party libraries like AsyncTCP and espAsyncWebServer providing asynchronous capabilities improving performance significantly compared synchronous counterparts mentioned earlier[^2].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

物联网老王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值