TCP ESP32 two-way communication
Posted: Fri May 12, 2023 9:57 am
Hello everyone, I found on the net a code for a two-way communication between two Wifi devices, via TCP. It's quite simple and works well, the only problem is that if one of the two switches off, when you switch it on again it doesn't connect, you have to turn them both off to re-establish the connection.
I made various tests but I can't, I ask, can someone help me? for me and for other people, because this sketch could be very offensive to others.
Thank you
I made various tests but I can't, I ask, can someone help me? for me and for other people, because this sketch could be very offensive to others.
Thank you
- #include <WiFi.h>
- const char* ssid = "ESP32-AP";
- const uint16_t portNumber = 50000; WiFiServer server(portNumber);
- WiFiClient client;
- bool connected = false;
- void setup() {
- Serial.begin(115200); Serial.println();
- Serial.print("Setting AP (Access Point)…");
- WiFi.softAP(ssid);
- IPAddress IP = WiFi.softAPIP();
- Serial.print(" -> IP address: "); Serial.println(IP);
- server.begin();
- }
- void loop() {
- if (!connected) {
- delay(5000);
- client = server.available();
- if (client) {
- Serial.println("Got a client !");
- if (client.connected()) {
- Serial.println("and it's connected!");
- connected = true;
- } else {
- Serial.println("but it's not connected!");
- client.stop();
- }
- }
- } else {
- if (client.connected()) {
- while (client.available()) Serial.write(client.read());
- while (Serial.available()) {
- char r = Serial.read();
- Serial.write(r);
- client.write(r);
- }
- } else {
- Serial.println("Client is gone");
- client.stop();
- connected = false;
- }
- }
- }
- ]
- [
- #include <WiFi.h>
- const char* ssid = "ESP32-AP";
- const uint16_t portNumber = 50000;
- IPAddress serverIP;
- WiFiClient client;
- bool connected = false;
- void setup() {
- Serial.begin(115200); Serial.println();
- Serial.print("Connecting to SSID:"); Serial.println(ssid);
- WiFi.mode(WIFI_STA);
- WiFi.disconnect();
- WiFi.begin(ssid);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.write('.');
- }
- Serial.println(".\nConnected");
- Serial.print("Local IP = "); Serial.println(WiFi.localIP());
- serverIP = WiFi.gatewayIP();
- Serial.flush();
- }
- void loop() {
- if (! connected) {
- if (client.connect(serverIP, portNumber)) {
- Serial.print("Connected to Gateway IP = "); Serial.println(serverIP);
- connected = true;
- } else {
- Serial.print("Could NOT connect to Gateway IP = "); Serial.println(serverIP);
- delay(500);
- }
- } else {
- while (client.available()) Serial.write(client.read());
- while (Serial.available()) {
- char r = Serial.read();
- Serial.write(r);
- client.write(r);}
- }
- }]