5

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.

mpromonet
  • 11,326
  • 43
  • 62
  • 91
Sadeq
  • 179
  • 1
  • 3
  • 14
  • Please provide more code, seeing both sides will help. – Marged Oct 16 '15 at 19:00
  • @Marged: I'd assume that, too, but "doesn't receive" doesn't imply "but the program executes successfully on the sending side". – Marcus Müller Oct 16 '15 at 19:05
  • my sending side is SocketProtocol app when I click on send button thats status change to sending message!I think that cant send message! – Sadeq Oct 16 '15 at 19:54
  • 1
    Did you look to the [telnet sample](https://github.com/esp8266/Arduino/blob/esp8266/hardware/esp8266com/esp8266/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino) ? – mpromonet Oct 17 '15 at 22:34
  • wow!thanks very much mpromonet .that's work correctly!Its a useful link. – Sadeq Oct 18 '15 at 13:33
  • Non-blocking: https://arduino.stackexchange.com/questions/40271/how-to-create-a-simple-tcp-server-with-the-analogread-value-on-wemos-d1-mini based on Telnet Sample here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino – handle Jan 16 '20 at 10:48

1 Answers1

4

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.

mpromonet
  • 11,326
  • 43
  • 62
  • 91