Authoring server

Because we are using ESP8266 as a client, we need to write a server for it to access. IDEA is used here to create a SpringBoot project to build a simple server.

(1) Create a project

(2) Modify the port

(3) writing the Controller

For convenience, use it here@RestControllerReturns a string directly

(4) Run the test

Start the SpringBoot service and you can see that Tomcat is running on port 8080.

Use a browser to access the local PC/helloInterface:



The server returns a string successfully, and the simple server setup is complete. Next, we use ESP8266 as a client to access the server.

Write the ESP8266 client

/** * This program uses ESP8266 as a client to access the local server */

#include <ESP8266WiFi.h>

#ifndef STASSID
#define STASSID "Your Wi-Fi Name"
#define STAPSK  "Your Wi-Fi password"
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;

const char* host = "Your server IP (local IP)";
const uint16_t port = 8080; // Your server port

static bool requestOnce = true; // Use variable control for only one access

// Send an HTTP request to the server
void httpRequest(a){
  // Create a WiFi client object with the object name client
  WiFiClient client;
 
  // Create a string for HTTP requests
  // "hello" is set to "hello" in @requestMapping.
  String httpRequest =  String("GET /hello") + "HTTP / 1.1 \ r \ n" +
                        "Host: " + host + ":" + port + "\r\n" +
                        "Connection: close\r\n" +
                        "\r\n";
  
  Serial.print("Connecting to "); 
  Serial.print(host); 
 
  if (client.connect(host, port)){ 
    Serial.println(" Success!");
    // The client sends a GET request
    client.print(httpRequest);
    Serial.println("Sending request: ");
    Serial.println(httpRequest);     
    
    Serial.println("Web Server Response:");        
    while (client.connected() || client.available()){ 
      if (client.available()){
        String line = client.readStringUntil('\n');
        Serial.println(line);
      }
    }
    
    client.stop(); // Disconnect from the server
    Serial.print("Disconnected from ");
    Serial.print(host);
    
  } else {
    // If the connection fails, output the connection failed message through the serial port
    Serial.println(" connection failed!"); client.stop(); }}void setup(a) {
  Serial.begin(115200);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while(WiFi.status() ! = WL_CONNECTED) { delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop(a) {
  if (requestOnce) {
    httpRequest();
    requestOnce = !requestOnce;
  } 
}
Copy the code

A serial port results