Six, use ESP32 to build a network server (1)

Insert picture description here

Basic web server

When we use ESP32 to contact the web server function, let’s first understand the role of the client and the server in the communication, as well as their respective main functions. The following is Baidu's information and personal opinions for reference only, welcome corrections

Client : The client can be understood as one of the two requirements. The client proposes to the server what kind of resource it needs. This resource may be a picture, video, document, etc., which we understand as a client request

Server : When describing the client, we know that the client will put forward his needs. Here, the server is used to respond to the demand. The client needs a picture. The server will send a picture to the client and the document will be sent to the client.

If we do not have the resources or for whatever reason can not be sent to the client, then here are two cases will occur
one kind of client service needs to correct this image and good and can be sent to the client, it can be sent past
the first The second situation is that the server does not have this picture or the picture cannot be sent out. At this time, a 404 error will occur. Here we understand it as the response of the server.

Server response and client request

The purpose of our study in this issue is to use ESP32 as a server to respond to requests from clients. Here, the client chooses to use a computer to request ESP32 data. The requested data is " Hello world! " as an example, which is more complex pictures and videos.
We will come into contact slowly later. Next, we will use the computer as the client to use the browser to request the data suggested by ESP32. What we need to do on the ESP32 side is to respond to the computer’s request.

Procedure flow chart

establish connection

At the beginning of the program, we must choose a way to establish a connection with the computer. The computer sends out a hot spot and uses ESP32 to connect or ESP32 sends out a hot spot and uses a computer to connect. Of course, it can also be connected to the router. Here we choose the computer to connect to the ESP32 hot spot, ESP32 The hotspot reference code is as follows (we will not explain the serial communication part of the program here)

  const char *AP_SSID="OnePlus 8 Pro";
  const char *AP_Password="122232542jxl";

  WiFi.softAP(wifi_SSID,wifi_Password);  //设置AP模式热点的名称和密码,密码可不填则发出的热点为无密码热点
  
  Serial.print("\n ESP32建立的wifi名称为:");
  Serial.print(wifi_SSID);  //串口输出ESP32建立的wifi的名称
  Serial.print("\nESP32建立wifi的IP地址为:");
  Serial.print(WiFi.softAPmacAddress());  //串口输出热点的IP地址

The main code is WiFi.softAP(wifi_SSID,wifi_Password);that the function function is to open the hotspot of ESP32. Among them wifi_SSID, wifi_Passwordthey are the name and password of the hotspot, which can be defined by yourself or refer to the previous article. The
following Serial.print()statements are some debugging information we need, see the code The output information is the name of the hotspot and ESP32. IP地址
After completing the above steps, we can connect to the hotspot of ESP32 through a computer. Next, we will enable the function of the web server.

Turn on the web server

The web server part is what we are new to. In this example, we need to understand some functions in the WebServer.h library used, and we can also directly refer to the library file. Of course, we must also call in the program before using this library. This library

virtual void begin()

Function function: start the server

void on(const String &uri, HTTPMethod method, THandlerFunction fn)

Function function: when the web server is established, a client makes an HTTP request, use this function to set the callback function corresponding to the request.
Parameters::
urithe resource requested by the
methodclient: set the method to respond to the client request, optional The method is as follows
HTTP_ANY
HTTP_GET
HTTP_POST
HTTP_PUT
HTTP_PATCH
HTTP_DELETE
HTTP_OPTIONS
fn: the callback function corresponding to the received request

void onNotFound(THandlerFunction fn)

Function function: When the resource address requested by the client is invalid or not available, this function will respond and use this function to set the corresponding callback function

Parameters::
fnthe callback function corresponding to the received request

void send(int code, char* content_type, const String& content)

Function function: use this function to send information to the client

Parameters::
codeHTTP response status code sent to the client, you can refer to the part of the response status code in the HTTP protocol information
content_type: the type of response content, you can also refer to the definition in the HTTP protocol
content: the content of the response to the client

virtual void handleClient()

Function function: processing the client's request, when the function is executed once, it will check whether there is any unprocessed client request and process the response

With the above functions, we can build a basic web server and respond. Below we see the code of the written web server part

  #include<WebServer.h>

  WebServer  esp32_server(80);  //声明一个 WebServer 的对象,对象的名称为 esp32_server
                              //设置网络服务器响应HTTP请求的端口号为 80

  esp32_server.begin();  //启动网络服务器
  esp32_server.on("/HolleWorld",HTTP_GET,handleRoot);  //函数处理当有HTTP请求 "/HolleWorld" 时执行函数 handleRoot 
  esp32_server.onNotFound(handleFound);  //当请求的网络资源不在服务器的时候,执行函数 handleFound 
  

Part of the code above #include<WebServer.h>call library program header should be placed
after the function esp32_server.begin();used to start the initialization function of the server
function esp32_server.on("/",HTTP_GET,handleRoot);of /HolleWorldthe resource request, HTTP_GETin response to the request method, which can refer to some of the specific HTTP协议relevant information, handleRootcall when the response to the request function, that is when there are received http://ESP32IP地址/HolleWorldwhen this request function called back our establishment will perform handleRootthe function of
esp32_server.onNotFound(handleFound);this function is very similar to the previous, address customer requests or when resources did not execute the functionhandleFound

Here we see the response of the two functions handleRootand handleFoundcontent of the response

void handleRoot()  //该函数内为处理网站根目录 “/” 时所执行的内容
{
    
    
  esp32_server.send(200,"text/plain","Holle World!");  //用函数 send 向浏览器发送信息,200表示正常状态码,text/plain表示发送的内容为纯文本类型 text/html为HTML的网页信息,"Holle World!"为发送的内容
  }

void handleFound()
{
    
    
  esp32_server.send(404,"text/plain","404:Not Found!");  //用函数 send 向浏览器发送信息,404表示服务器上找不到请求的资源,text/plain表示发送的内容为纯文本类型,"404:Not Found!"为发送的内容
  }
  

The above two functions make different responses to different client requests so that different content is displayed on the client browser. The
server needs to constantly check whether there is a client request and respond in response, so we need to put in the loopfunction Always call the handleClient()function in a loop to check whether there is a client request. The following is an example of the loop function, which is relatively simple

void loop() {
    
    
  // put your main code here, to run repeatedly:
  esp32_server.handleClient();
}

Client authentication

The complete source code will be posted at the end of the article. If necessary, you can copy it or leave a message to obtain the information file. After learning the above related information, write the program and burn it to the ESP32 development board. Open the serial monitor and press the reset button. See the returned debugging information in the serial monitor

Insert picture description here
We get to see the IP address 192.168.4.1, ESP32 default of this parameter is the IP, some people may be different in their own subject, let's use a computer connected to wifi, and enter in the browser 192.168.4.1/HolleWorldafter the browser is opened we will find A paragraph of text HolleWorld!appears on the browser interface . If it does, then our function esp32_server.on("/HolleWorld",HTTP_GET,handleRoot);is successfully called. After that, we enter 192.168.4.1/xxxxxx and fill in casually. As long as it is not HolleWorld, observe whether the browser interface appears 404:Not Found!to verify esp32_server.onNotFound(handleFound);whether the relevant program is correct. Remember to upload the program. All operations need to be established on the premise that the computer has been connected to the ESP32 hotspot.

Insert picture description here

to sum up

This time using ESP32 to build a basic web server, compared with the previous article about HTTP data types, status codes, etc., some students may find it more difficult to understand. After understanding the relevant Baidu HTT protocol format, it will be easier to understand, and you need code information. Students can leave a message in the mailbox below, or communicate with each other, everyone can learn from each other and make progress!

Complete code

#include<WiFi.h>
#include<WebServer.h>

WebServer  esp32_server(80);  //声明一个 WebServer 的对象,对象的名称为 esp32_server
                              //设置网络服务器响应HTTP请求的端口号为 80

const char *AP_SSID="OnePlus 8 Pro";
const char *AP_Password="122232542jxl";
void setup() {
    
    
  // put your setup code here, to run once:
  Serial.begin(115200);  //初始化串口通信并设置波特率为115200

  WiFi.softAP(AP_SSID,AP_Password);  //设置AP模式热点的名称和密码,密码可不填则发出的热点为无密码热点

  Serial.print("\n ESP32建立的wifi名称为:");
  Serial.print(AP_SSID);  //串口输出ESP32建立的wifi的名称
  Serial.print("\nESP32建立wifi的IP地址为:");
  Serial.print(WiFi.softAPIP());  //串口输出热点的IP地址

  esp32_server.begin();  //启动网络服务器
  esp32_server.on("/HolleWorld",HTTP_GET,handleRoot);  //函数处理当有HTTP请求 "/" 时执行函数 handleRoot 
  esp32_server.onNotFound(handleFound);  //当请求的网络资源不在服务器的时候,执行函数 handleFound 

void loop() {
    
    
  // put your main code here, to run repeatedly:
  esp32_server.handleClient();
}

void handleRoot()  //该函数内为处理网站根目录 “/” 时所执行的内容
{
    
    
  Serial.print("客户端访问!");
  esp32_server.send(200,"text/plain","Holle World!");  //用函数 send 向浏览器发送信息,200表示正常状态码,text/plain表示发送的内容为纯文本类型 text/html为HTML的网页信息,"Holle World!"为发送的内容
  }

void handleFound()
{
    
    
  esp32_server.send(404,"text/plain","404:Not Found!");  //用函数 send 向浏览器发送信息,404表示服务器上找不到请求的资源,text/plain表示发送的内容为纯文本类型,"404:Not Found!"为发送的内容
  }

Guess you like

Origin blog.csdn.net/qq_42250136/article/details/110084007