how create TCP server by ESP8266?

六月ゝ 毕业季﹏ 提交于 2020-01-01 03:40:33

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/33177722/how-create-tcp-server-by-esp8266

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!