TCP client

#include 

const char* ssid = "zjj";//连接你的wifi//
const char* password = "88888888";//连接你的密码//
const char* host = "192.168.43.1";//你的IP地址//
int ledPin = 2; //定义数字2接口d4//

void setup()//开机只运行一次//
{
  Serial.begin(115200);//设置波特率//
  Serial.println();
  pinMode(ledPin, OUTPUT);//定义小灯接口为输出接口
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)//连接不成功就一直打点//
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");//连接成功//
}

void loop()
{
  WiFiClient client;//类型定义//

  Serial.printf("\n[Connecting to %s ... ", host);
  if (client.connect(host, 5000))//连接指定IP地址和端口号//
  {
    Serial.println("connected]");
    Serial.println("[Sending a request]");//串口打印//
    client.print("123");//客户向服务器打印123//
    Serial.println("[Response:]");
    while (client.connected() || client.available())
    {
      if (client.available())
      {
        String line = client.readStringUntil('\n');//客户端向服务器读取字符串以\n结尾//
        Serial.println(line[0]);
        if (line[0]=='a')
        {
          Serial.println("LED ON");
          digitalWrite(ledPin, LOW); //点亮小灯
          }
        else if(line[0]=='g')
        {
           Serial.println("LED off");
           digitalWrite(ledPin, HIGH); //熄灭小灯
          }
      }
    }
    client.stop();
    Serial.println("\n[Disconnected]");
  }
  else
  {
    Serial.println("connection failed!]");
    client.stop();
  }
  //delay(5000);
}

你可能感兴趣的:(TCP client)