https://github.com/me-no-dev/ESPAsyncWebServer 里面有参考实例和源文件
该库还支持WebSocket、EventSource
头文件:
#include <Arduino.h>
#ifdef ESP32
#include <WiFi.h>
#include <AsyncTCP.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#endif
#include <ESPAsyncWebSrv.h>
一、HTTP请求 (代码片段):
#include <ESPAsyncWebServer.h> //引入相应库
AsyncWebServer server(80); //声明WebServer对象
void handleRoot(AsyncWebServerRequest *request) //回调函数
{
Serial.println("User requested.");
request->send(200, "html", "<div>Hello World!</div>"); //向客户端发送响应和内容
}
void setup()
{
server.on("/", HTTP_GET, handleRoot); //注册链接"/"与对应回调函数
server.on("/change", HTTP_GET, [] (AsyncWebServerRequest *request) {
String name;
if (request->hasParam("name")) {
name = request->getParam("name")->value();
val = atof(String(request->getParam("val")->value()).c_str());
if(name == "Z"){
Z = val;
int pwmVal = map((int)val,0,100,1023,0); // 用户请求数值为0-100,转为0-1023
ledcWrite(0, pwmVal);//指定通道输出一定占空比波形
}else if(name == "A"){
A = val;
}else if(name == "B"){
B = val;
}
} else {
name = "No message sent";
}
request->send(200, "text/plain", "Hello, GET: " + name);
});
server.begin(); //启动服务器
}
void loop(){}
1、方法说明:
ESPAsyncWebServer中对于请求的调取实在回调函数中进行的,回调函数传入一个 AsyncWebServerRequest
对象
request->version(); // uint8_t: 0 = HTTP/1.0, 1 = HTTP/1.1
request->method(); // enum: HTTP_GET, HTTP_POST, HTTP_DELETE, HTTP_PUT, HTTP_PATCH, HTTP_HEAD, HTTP_OPTIONS
// HTTP_GET = 0b00000001, HTTP_POST = 0b00000010, HTTP_DELETE = 0b00000100, HTTP_PU = 0b00001000, HTTP_PATCH = 0b00010000, HTTP_HEAD = 0b00100000, HTTP_OPTIONS = 0b01000000, HTTP_ANY = 0b01111111
request->url(); // String: URL of the request (not including host, port or GET parameters)
request->host(); // String: The requested host (can be used for virtual hosting)
request->contentType(); // String: ContentType of the request (not avaiable in Handler::canHandle)
request->contentLength(); // size_t: ContentLength of the request (not avaiable in Handler::canHandle)
re