Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how create TCP server by ESP8266?

I want to create a simple Wifi TCP server by ESP8266 in Arduino IDE. But I have a big problem: when I send a character or string from client I can't receive it on the server.

In fact I connect esp8266 to my PC and I want to see send character from client in pc terminal. my sending side is Socket protocol app for android!and complete code I write in sever side is:

WiFiServer server(8888);
void setup() 
{
  initHardware();
  setupWiFi();
  server.begin();
}
void loop() 
{
  WiFiClient client = server.available();
  if (client) {
    if (client.available() > 0) {
      char c = client.read();
      Serial.write(c);
    }
  }
}
void setupWiFi()
{
  WiFi.mode(WIFI_AP);
  WiFi.softAP("RControl", WiFiAPPSK);
}

void initHardware()
{
  Serial.begin(115200);
}

Baudrate it set to 115200 on both sides.

like image 668
Sadeq Avatar asked Sep 27 '22 11:09

Sadeq


1 Answers

In the loop, you are closing the client connection as soon as it is established deleting the WiFiClient object.

In order to keep the connection open you could modify the loop like this :

WiFiClient client;
void loop() 
{
    if (!client.connected()) {
        // try to connect to a new client
        client = server.available();
    } else {
        // read data from the connected client
        if (client.available() > 0) {
            Serial.write(client.read());
        }
    }
}

When client is not connected it tries to connect one and when a client is connected, it reads incoming data.

like image 73
mpromonet Avatar answered Dec 05 '22 18:12

mpromonet