本帖最后由 跋扈洋 于 2020-12-7 14:09 编辑

实验要求

通过将ESPDuino开发板设置成TCP Client模式,从而达到联网通信


具体方法

登录http://tcp.doit.am获取要使用的IP和端口:

程序
  1. <font _mstmutation="1"><font _mstmutation="1"><font _mstmutation="1">#include<ESP8266WiFi.h>
  2. const char*ssid ="STM32L476";
  3. const char*password ="284122348";
  4. const char*serverIP ="115.29.109.104";
  5. int serverPort =6558;
  6. WiFiClient client;
  7. bool bConnected =false;
  8. char buff[512];
  9. int nm =0;
  10. void setup(){
  11.   Serial.begin(115200);
  12.   delay(10);
  13.   Serial.println();
  14.   Serial.println();
  15.   Serial.print("Connecting to");
  16.   Serial.println(ssid);
  17.   WiFi.begin(ssid,password);
  18.   while(WiFi.status()!=WL_CONNECTED){
  19.     delay(500);
  20.     Serial.print(".");
  21.   }
  22.   Serial.println("WiFi connected");
  23.   Serial.println("IP address:");
  24.   Serial.println(WiFi.localIP());
  25. }
  26. void loop(){
  27.   delay(1);
  28.   if(bConnected ==false)
  29.   {
  30.     if(!client.connect(serverIP,serverPort))
  31.   {
  32.   Serial.println("connection failed");
  33.   delay(5000);
  34.   return;
  35. }
  36. bConnected=true;
  37. Serial.println("connection ok");
  38. }
  39. else if(client.available())
  40. {
  41. Serial.println("data is coming");
  42. while(client.available())
  43. {
  44.   buff[nm++]=client.read();
  45.   if(nm>=511)break;
  46. }
  47. buff[nm]=0x00;
  48. nm=0;
  49. Serial.print(buff);
  50. client.print(buff);
  51. client.flush();</font></font></font>
  52.   }
  53. }
实验现象