实现步骤:
ESP32 开启 WiFi AP
模式创建 WiFi 热点 定义 IP 地址 创建 TCP Server
测试代码如下:
# include <WiFi.h>
# include <WiFiClient.h>
const char * ssid = "cc123" ;
const char * password = "espressif" ;
WiFiServer ServerPort ( 1234 ) ;
IPAddress LocalIP ( 192 , 168 , 4 , 22 ) ;
IPAddress Gateway ( 192 , 168 , 4 , 22 ) ;
IPAddress SubNet ( 255 , 255 , 255 , 0 ) ;
void setup ( ) {
Serial. begin ( 115200 ) ;
delay ( 1000 ) ;
WiFi. mode ( WIFI_AP) ;
WiFi. softAPConfig ( LocalIP, Gateway, SubNet) ;
WiFi. softAP ( ssid, password) ;
IPAddress ip = WiFi. softAPIP ( ) ;
Serial. println ( ) ;
Serial. print ( "AP IP address: " ) ;
Serial. println ( ip) ;
ServerPort. begin ( ) ;
}
void loop ( ) {
WiFiClient client = ServerPort. available ( ) ;
if ( client) {
Serial. println ( "New client connected" ) ;
while ( client. connected ( ) ) {
if ( client. available ( ) ) {
String data = client. readStringUntil ( '\n' ) ;
Serial. print ( "Received data: " ) ;
Serial. println ( data) ;
String response = "Server received: " + data;
client. println ( response) ;
}
}
client. stop ( ) ;
Serial. println ( "Client disconnected" ) ;
}
}
测试方式:
使用手机连接 ESP32 创建的 AP 热点 查看 UART0 日志打印,获取 TCP Server 的 IP 地址 使用手机端 TCP 调试 APP(网络助手
) 与 ESP32 创建的 TCP Server 建立连接