编写服务器
因为我们使用esp8266充当一个客户端,因此需要写一个服务器供其访问。
这里使用IDEA创建SpringBoot项目来构件一个简易的服务器。
(1)创建项目
(2)修改端口
(3)编写Controller
为了方便起见,这里使用@RestController
直接返回一个字符串
(4)运行测试
启动SpringBoot服务,可以看到提示Tomcat已经在8080端口上运行了。
使用浏览器访问本地
/hello
接口:
服务器成功返回字符串,至此简易服务器搭建完成,接下来我们使用ESP8266充当客户端来访问服务器。
编写ESP8266客户端
/**
* 该程序使用ESP8266充当客户端,访问本地服务器
*/
#include <ESP8266WiFi.h>
#ifndef STASSID
#define STASSID "你的Wi-Fi名称"
#define STAPSK "你的Wi-Fi密码"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "你的服务器ip(本地ip)";
const uint16_t port = 8080; // 你的服务器端口
static bool requestOnce = true; // 使用变量控制只进行一次访问
// 向服务器发送HTTP请求
void httpRequest(){
// 建立WiFi客户端对象,对象名称client
WiFiClient client;
// 建立字符串,用于HTTP请求
// 因为服务器Controller中@RequestMapping设置的是"hello",所以这里写"Hello"
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!");
// 客户端发送get请求
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(); // 断开与服务器的连接
Serial.print("Disconnected from ");
Serial.print(host);
} else {
// 如果连接不成功则通过串口输出“连接失败”信息
Serial.println(" connection failed!");
client.stop();
}
}
void setup() {
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() {
if (requestOnce) {
httpRequest();
requestOnce = !requestOnce;
}
}