gpt4 book ai didi

c++ - ESP32 转 ESP32 WiFi 服务器/客户端问题

转载 作者:行者123 更新时间:2023-12-03 12:47:41 24 4
gpt4 key购买 nike

我有一个 ESP32 作为客户端,另一个 ESP32 作为直接通信和户外使用的接入点。我已经在 AP 端设置了一个服务器,并希望客户端与其通信,但我似乎无法完成这项工作。

我想知道两件事:

  1. 如何从客户端向服务器发送或写入数据?
  2. 如何读取并显示从客户端发送到服务器的数据?

我已附上以下代码:

AP/服务器代码

//SERVER
//Load Wi-Fi library
#include <WiFi.h>

// Replace with your network credentials
const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";
//Set web server port number to 80

WiFiServer server(80);


void setup() {
Serial.begin(115200);
Serial.println("Setting AP (Access Point)…");

WiFi.softAP(ssid, password);

IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address ");
Serial.println(IP);
Serial.print("MAC address ");
Serial.println(WiFi.softAPmacAddress());

server.begin();

}

void loop(){

WiFiClient client = server.available(); //Listen for incoming clients

if (client)
{ //If a new client connects,
Serial.println("New Client."); //print a message out in the serial port





while (client.connected())
{
Serial.println("Client connected.");
Serial.println(client.available());

if (client.available() > 0)
{
// read the bytes incoming from the client:
char thisChar = client.read();
// echo the bytes back to the client:
server.write(thisChar);
// echo the bytes to the server as well:
Serial.write(thisChar);
}


}
client.stop();
Serial.println("Client disconnected.");
Serial.println();
}
}

客户端代码

//Client
#include <WiFi.h>

const char* ssid = "ESP32-Access-Point";
const char* password = "SyedAhmedAli";


WiFiClient client;

IPAddress server(192, 168, 4, 1);

void setup()
{
Serial.begin(115200);
Serial.println();

Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println(" connected");
if(client.connect(server, 80))
{
Serial.println("connected to server");
client.write("Data");
}
else
{
Serial.println("failed to connect to server");
}

}


void loop()
{

}

最佳答案

除了前面的答案,您可以使用 espnow 作为各种 esp32 之间的协议(protocol)。这里是example .

关于c++ - ESP32 转 ESP32 WiFi 服务器/客户端问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53682815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com