esp32 tcp客户端
时间: 2023-05-14 20:05:37 浏览: 201
如下是一个简单的 ESP32 TCP 客户端的示例代码:
```c
#include <WiFi.h>
#include <WiFiClient.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* server_ip = "server_IP";
const int server_port = 80;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
WiFiClient client;
if (client.connect(server_ip, server_port)) {
Serial.println("Connected to server");
client.println("GET / HTTP/1.1");
client.println("Host: server_IP");
client.println("Connection: close");
client.println();
while (client.connected()) {
String line = client.readStringUntil('\n');
Serial.println(line);
}
client.stop();
Serial.println("Disconnected from server");
} else {
Serial.println("Failed to connect to server");
}
delay(5000);
}
```
这个代码使用 ESP32 连接到一个 TCP 服务器,并发送一个 HTTP GET 请求,然后读取服务器的响应并打印到串口上。你需要将代码中的 `your_SSID`、`your_PASSWORD` 和 `server_IP` 替换为你的 Wi-Fi SSID、密码和服务器 IP 地址。
阅读全文