HTTP protocol data communication-the client sends data information to the server-the server

HTTP protocol data communication-the client sends data information to the server-the server


This experiment uses two ESP8266s, one as the server and the other as the client.

The server receives the HTTP request sent by the client, parses the parameter value carried in the GET request, and controls its own onboard LED light to turn on and off based on the parameter value.

The following is the server program:

/*
 * 服务端程序:
 * 接收客户端发来的http请求并且解析信信息中的数据信息
 * 将解析的数据通过串口监视器显示供用户查看
 * 将解析的客户端按键状态信息用于控制服务器端板上的LED的点亮和熄灭
 */
 #include <ESP8266WiFi.h>
 #include <ESP8266WiFiMulti.h>
 #include <ESP8266WebServer.h>  //http服务端库

 ESP8266WiFiMulti wifiMulti;      //ESP8266WiFiMulti对象
 ESP8266WebServer webServer(80);  //建立网络服务器对象,用于响应http请求。监听端口80

 IPAddress local_IP(192,168,0,111);//设置ESP8266联网后的IP
 IPAddress gateway(192,168,0,1);//设置网关IP,(通常是wifi路由的IP)
 IPAddress subnet(255,255,255,0);//设置子网掩码
 IPAddress dns(192,168,0,1);//设置局域网DNS的IP(通常局域网DNS的IP是wifi路由的IP)  

 void setup(){
  Serial.begin(9600);
  Serial.println("");

  pinMode(LED_BUILTIN,OUTPUT);//LED_BUILTIN 是一个宏,在库中已经定义,它代表13引脚
  digitalWrite(LED_BUILTIN,HIGH);

  //设置开发板网络
  if(!WiFi.config(local_IP,gateway,subnet)){
    Serial.println("Failed to Config ESP8266 IP");
  }

  wifiMulti.addAP("1124","11241124");
  Serial.println("Connecting...");

  while(wifiMulti.run() != WL_CONNECTED){
    delay(250);
    Serial.print(".");
  }
  
  Serial.print("\n");
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());
  Serial.print("IP address: \t");
  Serial.println(WiFi.localIP());

  webServer.on("/update",handleUpdate);//处理服务器更新函数。当有客户端向服务器发送HTTP请求时,设置HTTP请求回调函数
  webServer.begin();//启动网络服务

  Serial.println("HTTP Server Started!");
 }

void loop(){
  webServer.handleClient();//检查http服务器访问
}

void handleUpdate(){
  float floatValue = webServer.arg("float").toFloat();//获取客户端发送http信息中的浮点数值
  int intValue = webServer.arg("int").toInt();//获取int值
  int buttonValue = webServer.arg("button").toInt();//按键控制量

  webServer.send(200,"text/plain","Received");//发送http响应

  buttonValue == 0?digitalWrite(LED_BUILTIN,LOW):digitalWrite(LED_BUILTIN,HIGH);
  
  //串口监视器输出获取到的变量数值
  Serial.print("floatValue = ");
  Serial.println(floatValue);

  Serial.print("intValue = ");
  Serial.println(intValue);

  Serial.print("buttonValue = ");
  Serial.println(buttonValue);
  Serial.println("*********************");
}
 

client program

Guess you like

Origin blog.csdn.net/X_King_Q/article/details/112209461